for
计算圆周率
使用无穷级数展开式
y = 0;
g = -1;
n = input('n = ? ');
for i = 1 : n
g = -g;
y = y + g/(2*i-1);
end
pai = 4*y
用向量表示更直观,符合MATLAB的特点
n = input('n = ? ');
x = 1 : 2 : (2 * n - 1);
y = (-1).^(2 : n+1)./ x;
pai = sum(y) * 4
使用定积分求
a = 0;
b = 1;
n = input('n=? ');
h = (b - a) / n;
x = a : h : b;
f = sqrt(1-x.*x);
s = [];
for k = 1 : n
s1 = (f(k) + f(k+1))*h /2;
s = [s, s1];
end
pai = 4 * sum(s)
- 蒙特卡洛法
s = 0;
n = input('n = ');
for i = 1 : n
x = rand(1);
y = rand(1);
if x * x + y * y <= 1
s = s + 1;
end
end
pai = s / n * 4
for更一般的格式