Re: Print value of p from the infinite series



Lea0x.Diz@xxxxxxxxx wrote:
3.142186 3.142 true 3142 1685
3.141000 3.141 false 3140 1686
3.142185 3.142 true 3142 1687
3.141000 3.141 false 3141 1688
But hey, isn't that term at 1686 should terminate the for-loop, and
the `p in int' should yield 3141,

Why do you think that?

but it return 3140 and take another extra loops to complete, weird, huh?

No. Perfectly explicable. Stay tuned.

final double four = 4.0;

Why did you do this?

double p = 0.0;
int count = 0;
boolean flag = true;

System.out.printf("%s%11s%14s%14s%13s\n", "full:", "p:", "flag:",
"p in int:", "counter:");

for (int i = 1; (int)(p * 1000) != 3141; i += 2) {
++count;
p = (flag) ? (p + (four/i) ) : ( p - (four/i));
System.out.printf("%f %10.3f %9b %13d %12d\n", p, p, flag,
(int)(p * 1000), count);
flag = !flag; // switch back and forth
}

Your problem is in the expression (int)(p * 1000), which on iteration 1686 equals 3140 because p is less than 3.141000.

.. . .

Yes, it is. Not much less, less than one ulp over seven decimal places, but less. The printf() rounds the value for display.

- Lew
.



Relevant Pages