ä¸é¢æ¯äºç§æ¹æ³å®ç°çã代ç ä½ å¯ä»¥ç´æ¥ç¨äºãæ¹æ³æ¯è¾å¨wikiä¸é¢å°±æãç¾åº¦ä¸è®©æè´´ä¸æ¥ãä½ å¯ä»¥èªå·±å»æ¾ãæè
çä¸é®ç®±æç»ä½ åè¿å»ã
1. monte-carlo method
samplesize = 1e6 ; % set the size of the samples
x = 2*rand(1, samplesize ) - 1 ; % generate x
y = 2*rand(1, samplesize ) - 1 ; % generate y
PI = sum(sum(sqrt(x.^2+y.^2)<=0.5))/1e6*4 ; % calcualte pi
2. geometric circle method
scale = 1000 ; % set the scale of the square
[X, Y] = meshgrid(-scale :scale , -scale :scale ) ; % create the grid
PI = sum(sum(sqrt(X.^2+Y.^2)<=scale*2 +0.5))/(scale+1)^2*4 ;
3. Trigonometry Method
PI = 4*( 4*atan(1/5)-atan(1/239) ) ; % atan can be caicluate by taylor series
4. Gauss-Legendre algorithm
N = 100 ; % set iteration number
a0 =1; t0 = 1/sqrt(2) ; b0 = 1/sqrt(2) ; p0 = 1; % init
for n = 1:N
a1 = (a0+b0)/2 ;
b1 = sqrt(a0*b0) ;
t1 = t0 - p0*(a0-a1)^2;
p1 = 2*p0;
a0 = a1 ;
b0 = b1 ;
t0 = t1 ;
p0 = p1 ;
end
PI = (a1+b1)^2/(4*t1) ; % get pi
5. BBP formula
N = 100 ; % number of iteration
PI = 0 ; % init
for n = 0:N
PI = PI + (4/(8*n+1)-2/(8*n+4)-1/(8*n+5)-1/(8*n+6))*(1/16)^n ;
end
温馨提示:答案为网友推荐,仅供参考