Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pi becomes inaccurate with increasing the number of samples

When I change the value on line 28(which I pointed out with an arrow) from 0.00001 to 0.000001 the value of Pi becomes inaccurate. It's counterintuitive to me as to how increasing precision will make the value wrong? The program is simply supposed to calculate pi using the integral of 4 / (1 + x*x) over 0 to 1.

#include <iostream>

void fourOverX2(float& value, 
        const float lowerLimit, 
        const float upperLimit,
        const float dx)
{
    std::cout << "Values Sent: \n" 
    << lowerLimit << "\n" << upperLimit 
    << "\n" << dx << std::endl;

    value = 0;

    float x = lowerLimit, numerator = 4 * dx;

    while(x < upperLimit)
    {
        value += numerator / (1 + x * x);
        x += dx;
    }
}


int main()
{
    float value;

    fourOverX2(value, 0, 1, 0.000001); // <---- doubt here

    std::cout << "PI: " << value << std::endl;

    return 0;
}

Associated output on my machine

like image 840
ayanhca02 Avatar asked Sep 19 '25 11:09

ayanhca02


1 Answers

Using N steps of size dx in left Riemann sums gives a method error of size dx and a accumulated floating point error of (relative) size N*mu. These balance at the minimum error which gives dx ~ sqrt(mu).

For 32bit floating point mu=2^-23, so the minimum error should occur for dx about 5*10^-4. Your two probes are well in the region of accumulated floating point.

Using 64bit floating point will shift the optimal step size to 10^-8. I'd recommend using a better integration scheme. With trivial modifications you can get the midpoint and trapezoidal methods. Still accessible should be the 4th order Simpson quadrature method. With higher order methods you get better accuracy and also the optimal error at larger step sizes.

like image 135
Lutz Lehmann Avatar answered Sep 21 '25 01:09

Lutz Lehmann