simpson.pl (1078B)
1 #!/usr/bin/env perl 2 # 3 # 4 # f(x) = 1 / (1 +x)とx軸とで囲まれた図形のうち閉区間[0,1]の範囲の面積 5 # 6 # 閉区間[0,1] で積分すると、∫ f(x) = [log(1 +x)] = log2 ( 0.693147...) 7 # 8 # [a,b]を2n等分して、h = (1/2n) * (b-a)とし、x_i = a + hi, y_i = f(x_i) ( i = 0,1,...,n)とする 9 # 面積 S = h/3{y_0 + 4(y_1+ y_3 + ...+ y_(2n-1)) + 2(y_1 + y_4 + ...+ y_(2n-2)) + y_2n} 10 # 11 12 13 use v5.40; 14 use autodie; 15 16 my $n = 2500; 17 my $a = 0; 18 my $b = 1; 19 20 say "f(x) = 1 / (1 + x)とx軸とで囲まれた図形のうち閉区間[0,1]の範囲の面積を求めます。"; 21 say "この区間を何等分しますか? : n = ", $n * 2; 22 23 my $h = (1 / (2 * $n)) * ($b - $a); 24 my $s = 0; 25 26 for (my $i = 0; $i <= 2 * $n; $i++) { 27 my $x_i = $a + $h * $i; 28 my $y_i = 1 / ( 1 + $x_i); 29 if ($i == 0) { 30 $s = ($h / 3) * $y_i; 31 } 32 33 if (($i > 0 ) and ($i < 2 * $n)) { 34 if ($i % 2) { 35 $s = $s + ($h / 3) * 4 * $y_i; 36 } else { 37 $s = $s + ($h / 3) * 2 * $y_i; 38 } 39 } 40 41 if ($i == 2 * $n) { 42 $s = $s + ($h / 3) * $y_i; 43 } 44 } 45 46 say "求める面積をSとすると S = ", $s;