实验31 Mathcad编程举例(3)-程序的递归 程序的递归调用实例 (1)计算和 age(n-1)+2 otherwise sum(n): =sum(n-1)+n if n>1 sum(100)=5050 (2)计算阶乘 n fac(n-1)otherwise fac(6)=720 (3)计算组合数 C(n, k) C(n-1,k-l)ifk≠0 k 1 otherwise C(6,2)=15 C(15,7)=6435 (4)计算菲波那契数列的项 ib(n): =fib(n-1)+fib(n-2)if n>1 fb(8)=34 fb(15)=987 (5)计算两个整数的最大公约数 Hed(m, n): =a< min(m, n) b←-max(m,n) od(b, a)=0 Hed(a, b-a) otherwise
Hcd(m, n) a ¬ min(m, n) b ¬ max(m, n) a if mod(b, a) = 0 Hcd(a , b - a) otherwise := (5) 计算两个整数的最大公约数: fib(8) = 34 fib(15) = 987 fib(n) fib(n - 1) + fib(n - 2) if n > 1 1 otherwise := (4) 计算菲波那契数列的项: C(6, 2) = 15 C(15, 7) = 6435 C(n, k) n k ×C(n - 1, k - 1) if k ¹ 0 1 otherwise := (3) 计算组合数: fac(6) = 720 fac(n) 1 if n = 0 n×fac(n - 1) otherwise := (2) 计算阶乘: sum(100) = 5050 sum(n) sum(n - 1) + n if n > 1 1 otherwise := age(8) = 44 age(n) 30 if n = 1 age(n - 1) + 2 otherwise := (1)计算和: 程序的递归调用实例: 实验31 Mathcad 编程举例(3) - 程序的递归
Hcd(105,855)=15Hcd(108,804)=12 (6)用有关公式计算π的近似值: A用wais公式计算π的近似值 P(n):=2 P(900)=3.4072059461076 4k"-1 Pivalue(n): =2 if n=0 1+ Pivalue(n-1)otherwise Lvalue(900)=3.14072059461076 B:用 Machin公式计算π的近似值: 1000 ∑ =3.14059265383979 p(n):=|pi(n-1)+(-1)2n-/ifn>1 4-pi(1000=3.14059265383979 c:编一个程序用如下公式计算π的近似值 2.46 d(n): =if n=1 d(n-1)otherwise 21 pi value(k):=|a← d(i (2i+1)2 (21+1) a
Hcd(105, 855) = 15 Hcd(108, 804) = 12 (6) 用有关公式计算p 的近似值: A 用Wallis公式计算p 的近似值: P(n) 2 1 n k 1 1 4 k 2 × - 1 + æ ç è ö ÷ Õ ø = := P(900) = 3.14072059461076 Pivalue(n) 2 if n = 0 1 1 4 n 2 × - 1 + æ ç è ö ÷ ø ×Pivalue(n - 1) otherwise := Pivalue(900) = 3.14072059461076 B : 用Machin公式计算 p 的近似值: 4 1 1000 k (-1) k-1 1 2k - 1 å × = × = 3.14059265383979 pi(n) pi(n - 1) (-1) n-1 1 2×n - 1 + × if n > 1 1 otherwise := 4×pi(1000) = 3.14059265383979 C : 编一个程序用如下公式计算p 的近似值: p 6 1 2 1 2 1 3 3 3 × + × 1×3 2×4 1 5 2 5 × + × 1×3×5 2×4×6 1 7 2 7 × = + × + ...... d(n) 1 2 if n = 1 2n - 1 2n ×d(n - 1) otherwise := pi_value(k) a 1 2 ¬ a a 1 (2×i + 1) 2 (2×i+1) × ¬ + ×d(i) for iÎ 1.. k 6×a :=
+1.1+13.11351 =3.14115513392857 2.453224-67,7 2 7
pi_value(17) = 3.14159265358959 6 1 2 1 2 1 24 + × 1×3 2×4 1 5×32 + × 1×3×5 2×4×6 1 7 2 7 × + × æ ç è ö ÷ ø × = 3.14115513392857