mPEC Forum

บทเรียน => การใช้โปรแกรม Mathematica => Topic started by: psaipetc on February 11, 2008, 01:13:22 PM



Title: วิธีทำ Trapezoidal Integration สามวิธีใน Mathematica
Post by: psaipetc on February 11, 2008, 01:13:22 PM
เขียนแบบ procedural ทั้งหมด:

trapezoidInt1[f_, a_, b_, n_] := Module[{delta, sum},
  delta = (b - a)/n;
  sum = 0;
  For[i = 0, i <= n, i++, sum = sum + f[a + i*delta]];
  delta (sum - (f[ a ] + f[ b ])/2)
  ]


เขียนแบบ procedural ผสม functional:

trapezoidInt2[f_, a_, b_, n_] := Module[{list, delta},
  delta = (b - a)/n;
  list = Table[f[a + i*delta], {i, 0, n}];
  delta (Apply[Plus, list] - (f[ a ] + f[ b ])/2)
  ]

เขียนแบบ functional หมด:
trapezoidInt3[f_, a_, b_, n_] := (b - a)/n (Apply[Plus, Table[f[a + i (b - a)/n], {i, 0, n}]] - (f[ a ] + f[ b ])/2)

ผลที่ได้เหมือนกัน
Table[{2^k, trapezoidInt1[Sin, 0., Pi/2, 2^k],  trapezoidInt2[Sin, 0., Pi/2, 2^k], trapezoidInt3[Sin, 0., Pi/2, 2^k]}, {k, 0, 10}] // TableForm

1   0.785398   0.785398   0.785398
2   0.948059   0.948059   0.948059
4   0.987116   0.987116   0.987116
8   0.996785   0.996785   0.996785
16   0.999197   0.999197   0.999197
32   0.999799   0.999799   0.999799
64   0.99995   0.99995   0.99995
128   0.999987   0.999987   0.999987
256   0.999997   0.999997   0.999997
512   0.999999   0.999999   0.999999
1024   1.   1.   1.