for

image.png
image.png
image.png
计算圆周率【MATLAB程序控制】for & while - 图4

  1. 使用无穷级数展开式 【MATLAB程序控制】for & while - 图5

    1. y = 0;
    2. g = -1;
    3. n = input('n = ? ');
    4. for i = 1 : n
    5. g = -g;
    6. y = y + g/(2*i-1);
    7. end
    8. pai = 4*y

    用向量表示更直观,符合MATLAB的特点

    1. n = input('n = ? ');
    2. x = 1 : 2 : (2 * n - 1);
    3. y = (-1).^(2 : n+1)./ x;
    4. pai = sum(y) * 4
  2. 使用定积分求

image.png

  1. a = 0;
  2. b = 1;
  3. n = input('n=? ');
  4. h = (b - a) / n;
  5. x = a : h : b;
  6. f = sqrt(1-x.*x);
  7. s = [];
  8. for k = 1 : n
  9. s1 = (f(k) + f(k+1))*h /2;
  10. s = [s, s1];
  11. end
  12. pai = 4 * sum(s)
  1. 蒙特卡洛法
    1. s = 0;
    2. n = input('n = ');
    3. for i = 1 : n
    4. x = rand(1);
    5. y = rand(1);
    6. if x * x + y * y <= 1
    7. s = s + 1;
    8. end
    9. end
    10. pai = s / n * 4

    for更一般的格式

image.png
image.png

while

while语句

image.png