简体   繁体   中英

error in loop with if statement, but gets compiled and terminates without error without displaying expected result

While solving the question(It is in the code as comment.) The if statement (which displays the result) is not working. Please help me to figure out the error. It gets compiled and runs but output is not displaying.

/*
 * (Calculating the Value of π ) Calculate the value of π from the infinite series
         4     4     4     4      4
π = 4 – --- + --- – --- + --- – ------ + ...
         3     5     7     9      11
Print a table that shows the value of π approximated by computing the first 200,000 terms of this
series. How many terms do you have to use before you first get a value that begins with 3.14159?
 */
public class ValueOfPi 
{
    public static void main(String[] args)
    {
        int i,count=0;
        double pi=0.0,n=1.0,PI=3.14159;
        for(i=0;i<200000;i++)
        {
            count++;
            if(count%2!=0)
            {
                pi=pi+(4/n);
            }
            else if(count%2==0)
            {
                pi=pi-(4/n);
            }
            n=n+2;
            if(pi==PI)
            {
                System.out.printf("terms=%d     PI=%f\n",count,pi);
                break;
            }
        }
    }
}

The reason that that the if statement is not working is that you're comparing floating point numbers for equality. The page What Every Computer Scientist Should Know About Floating-Point Arithmetic explains why.

After rereading the OP's question, for this case I'd first convert the calculated value of pi to a string that is 8 or more characters long and compare the first 7 characters against "3.14159".

First floating point is inprecise - an approximation of a sum of (negative) powers of two - (also with 3.14159), and the calculated pi can be above or below the given value.

Also use %n as \\n is a Linux line end, not Windows where it is \\r\\n . This could have prevented the flushing of the line buffer to output. (Not sure, I have Linux).

        if (Math.abs(pi - PI) < 1.0E-5)
        {
            System.out.printf("terms=%d     PI=%f%n",count,pi);
            break;
        }

Also you might use Math.PI for a better approximation. You now risk to have a more precise pi than PI needing that 0.00001 imprecision.

Using == or a too small eps margin, like 0.00000001 might cause an almost infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM