matlab上机作业求助

来源:百度知道 编辑:UC知道 时间:2024/05/29 07:44:41
上机实现计算π的各种方法,并比较个方法的优劣,如计算精度、计算量、计算时间等。有能力的话,通过查阅,寻找到计算π的新方法。
会的人能不能麻烦一下,明天就要交了。。。。。

下面是五种方法实现的。代码你可以直接用了。方法比较在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 ;