# Pastebin: halfpiarea.c

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. 息子に数値型やり方についてちょっと経験させるつもりでこれを書いたのです。

Format
Plain text
Post date
2016-09-24 21:31
Publication Period
Unlimited
` /* Computing the value of pi by integrating the area of a (half of a) circle. // by Joel Matthew Rees, 1 August 2013 // Copyright Joel Matthew Rees // // Fair use acknowledged. // // All rights to this expression of the method reserved. // // (Starting from scratch isn't that hard, // and you'll like the results better.) // // Compile with the right libraries: // cc -Wall -lm -o halfpiArea halfpiArea.c */    #include <stdio.h> #include <stdlib.h> #include <math.h>   int main( int argc, char * argv[] ) {    double area = 0.0;    double deltaX = 0.025;    double lastX = -1.0;    double x;    double almostPi;     if ( argc > 1 )    {  deltaX = strtod( argv[ 1 ], NULL );    }     /* Note that starting from the half delta converges at least one decimal digit faster.    // (That's because the height of the rectangle crosses the circle at midpoint,     // rather than left edge or right. Draw the pictures to see why.    // This is right edge, but changing to midpoint or left edge is trivial.)     */    for ( x = -1.0 + deltaX; x <= 1.0; x += deltaX )    {       double ysquared = 1.0 - ( x * x );       double y = sqrt( ysquared );       /* deltaX = x - lastX; */       lastX = x;       area += deltaX * y;       if ( deltaX > 0.00005 )       {  printf( "(%17.15g,%17.15g): %17.15g\n", x, y, area );       }    }     almostPi = area * 2;    printf( "Almost Pi: %17.15g\n", almostPi );    return EXIT_SUCCESS; }`