Search code examples
c++mathpi

Programm Output "nan"


I am trying to calculate PI with the infinite series. When I started my programm I excpected to get some wrong nummbers, but instead I get the output "nan".

Does anyone know why?

Here's the code:

#include <iostream>
using namespace std;

int main()
{
    long double pi;
    float x;
    int y = 3;
    bool loop = true;
    while(true)
    {
        x=1/y;
        y+2;
        if(loop == true)
        {
            pi -= x;
            loop = false;
        }
        else if(loop == false)
        {
            pi += x;
            loop = true;
        }
        cout<<pi<<" ";

    }
    return 0;
}

Solution

  • The behaviour of your code is undefined as pi is not initialised when you read its value on adding or subtracting x to or from it. That accounts for the NaN: some compilers helpfully - in some ways - set uninitialised floating point variables to NaN.

    x = 1 / y; sets x to 0 due to integer division. Did you want 1.0 / y?

    y + 2; is a no-op. Did you want y += 2?

    Note that you need to multiply the series by 4 to obtain pi, and this series converges especially slowly, some 300 terms are needed for two decimal places. And your starting value of y is wrong. Shouldn't it be 1?