Compute the value of pi by using numerical methods to integrate the area of a half circle. 半円の面積を数値積分を使って計算して π の値を計算する。 Wanted something to teach my son a little about numerical methods. 息子に数値型やり方についてちょっと経験させるつもりでこれを書いたのです。

格式
Plain text
提交日期
2016-09-24 21:31
Publication Period
Unlimited
  1. /* Computing the value of pi by integrating the area of a (half of a) circle.
  2. // by Joel Matthew Rees, 1 August 2013
  3. // Copyright Joel Matthew Rees
  4. //
  5. // Fair use acknowledged.
  6. //
  7. // All rights to this expression of the method reserved.
  8. //
  9. // (Starting from scratch isn't that hard,
  10. // and you'll like the results better.)
  11. //
  12. // Compile with the right libraries:
  13. // cc -Wall -lm -o halfpiArea halfpiArea.c
  14. */
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <math.h>
  18. int main( int argc, char * argv[] )
  19. {
  20. double area = 0.0;
  21. double deltaX = 0.025;
  22. double lastX = -1.0;
  23. double x;
  24. double almostPi;
  25. if ( argc > 1 )
  26. { deltaX = strtod( argv[ 1 ], NULL );
  27. }
  28. /* Note that starting from the half delta converges at least one decimal digit faster.
  29. // (That's because the height of the rectangle crosses the circle at midpoint,
  30. // rather than left edge or right. Draw the pictures to see why.
  31. // This is right edge, but changing to midpoint or left edge is trivial.)
  32. */
  33. for ( x = -1.0 + deltaX; x <= 1.0; x += deltaX )
  34. {
  35. double ysquared = 1.0 - ( x * x );
  36. double y = sqrt( ysquared );
  37. /* deltaX = x - lastX; */
  38. lastX = x;
  39. area += deltaX * y;
  40. if ( deltaX > 0.00005 )
  41. { printf( "(%17.15g,%17.15g): %17.15g\n", x, y, area );
  42. }
  43. }
  44. almostPi = area * 2;
  45. printf( "Almost Pi: %17.15g\n", almostPi );
  46. return EXIT_SUCCESS;
  47. }
下载 可打印视图

网址

Embed with JavaScript

Embed with iframe

原始文本