First Article

65 views

Posted: 27 Jul 2021 (10:06)
Last Edited: 29 Nov 2021 (09:49)

/dev/urandom

@cat

...

#define _USE_MATH_DEFINES
#include <math.h>
#include <iostream>
#include <iomanip>

/**
 * Estimate PI using Leibiniz series
 * 1 - (1/3) + (1/5) - (1/7) + (1/9) .... = (pi / 4)
 */

void calc(int terms) {
    long double pi = M_PI;

    long double sum = 0;
    long long int denom = 1;

    for(int i = 0; i < terms; i++) {
        sum += pow(-1, i) * ( 1 / double(denom) );
        denom += 2;
        long double estimate = sum * 4;
        long double diff = abs(pi - estimate);
        std::cout << std::setprecision(15) << std::fixed << estimate << "\t" << diff << "\n";
    }
} 

int main() {
    int terms = pow(10, 8); // Specify calculation upto n terms
    calc(terms);
}


imvkclh1hiuzwf09l1qh.png




Tags


code programming first cpp math

Comments