用matlab公式法计算pi的10种方法代码
时间: 2024-02-09 09:09:06 浏览: 208
以下是10种使用MATLAB公式法计算π的方法,每种方法的代码解释在注释中:
方法1:使用Machin公式计算π,Machin公式为:π/4 = 4arctan(1/5) - arctan(1/239)。
```matlab
pi_approx = 4 * (4 * atan(1/5) - atan(1/239));
```
方法2:使用Leibniz公式计算π,Leibniz公式为:π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
```matlab
n = 1000000; % 计算n项
pi_approx = 0;
for i = 0:n-1
pi_approx = pi_approx + (-1)^i / (2*i+1);
end
pi_approx = 4 * pi_approx;
```
方法3:使用Wallis公式计算π,Wallis公式为:π/2 = (2/1)*(2/3)*(4/3)*(4/5)*(6/5)*(6/7)*...
```matlab
n = 1000000; % 计算n项
pi_approx = 1;
for i = 1:n
pi_approx = pi_approx * ((2*i)^2) / ((2*i-1)*(2*i+1));
end
pi_approx = 2 * pi_approx;
```
方法4:使用Euler公式计算π,Euler公式为:π^2/6 = 1/1^2 + 1/2^2 + 1/3^2 + ...
```matlab
n = 1000000; % 计算n项
pi_approx = sqrt(6 * sum(1./(1:n).^2));
```
方法5:使用Gregory公式计算π,Gregory公式为:π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
```matlab
n = 1000000; % 计算n项
pi_approx = 0;
for i = 0:n-1
pi_approx = pi_approx + (-1)^i / (2*i+1);
end
pi_approx = 4 * pi_approx;
```
方法6:使用Brent-Salamin公式计算π,Brent-Salamin公式为:a_(n+1) = (a_n + b_n)/2, b_(n+1) = sqrt(a_n * b_n), π ≈ (a_n + b_n)^2 / (4 * a_n)。
```matlab
% 初始值
a = 1;
b = 1/sqrt(2);
t = 1/4;
n = 0;
while abs(a-b) > 1e-15
n = n + 1;
a_new = (a + b) / 2;
b_new = sqrt(a * b);
t_new = t - 2^n * (a - a_new)^2;
a = a_new;
b = b_new;
t = t_new;
end
pi_approx = (a + b)^2 / (4 * t);
```
方法7:使用Chudnovsky公式计算π,Chudnovsky公式为:1/π = 12*∑((-1)^k*(6*k)!/(k!)^3*(13591409+545140134k)/(640320^3)^k),其中k从0到正无穷。
```matlab
syms k;
n = 100;
pi_inv = 12 * sum((-1).^k * factorial(6*k) / (factorial(k))^3 * (13591409+545140134*k) / (640320^3)^k, 0, n-1);
pi_approx = 1 / sqrt(double(pi_inv));
```
方法8:使用Ramanujan公式计算π,Ramanujan公式为:1/π = 2√2/9801 * ∑(factorial(4*k)*(1103+26390*k)/(factorial(k)^4*396^(4*k)), k=0:inf)。
```matlab
syms k;
n = 100;
pi_inv = 2 * sqrt(2) / 9801 * sum(factorial(4*k)*(1103+26390*k)/(factorial(k).^4*396^(4*k)), 0, n-1);
pi_approx = 1 / double(pi_inv);
```
方法9:使用Bailey-Borwein-Plouffe公式计算π,BBP公式为:π = ∑(1/16^k*(4/(8k+1)-2/(8k+4)-1/(8k+5)-1/(8k+6))),其中k从0到正无穷。
```matlab
n = 100;
pi_approx = 0;
for k = 0:n-1
pi_approx = pi_approx + 1/16^k * (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6));
end
pi_approx = pi_approx * 1/16;
```
方法10:使用自定义公式计算π,例如以下公式:π/2 = ∑(1/n*(n+1/2)^2),其中n从1到正无穷。
```matlab
n = 1000000; % 计算n项
pi_approx = 0;
for i = 1:n
pi_approx = pi_approx + 1/i*((i+0.5)^2);
end
pi_approx = 2 * pi_approx;
```
阅读全文