Re: Print value of p from the infinite series
- From: "Leah" <Lea0x.Diz@xxxxxxxxx>
- Date: 26 Feb 2007 21:40:51 -0800
On Feb 27, 9:11 am, Lew <l...@xxxxxxxxxxxxxxxxxxxx> wrote:
Lea0x....@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?
Now, I get what you mean.
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?
constants value, anything wrong with 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
<code>
3.1421861 3.142 true 3142 1685
3.1409995 3.141 false 3140 1686 <--
3.1421854 3.142 true 3142 1687
3.1410002 3.141 false 3141 1688
</code>
Increase the precision reveal the caveat. "%.7f"
Now, I only thinking that is this the correct way to do it or not
accurate at all? Is it a sane way to change the expression to:
for (int i = 1; p != 3.141; i += 2)
some sort of that, but how to tell compiler only compare decimal
points as needed?
Any suggestions?
.
- Follow-Ups:
- Re: Print value of p from the infinite series
- From: Thomas Fritsch
- Re: Print value of p from the infinite series
- From: Lew
- Re: Print value of p from the infinite series
- References:
- Print value of p from the infinite series
- From: Lea0x . Diz
- Re: Print value of p from the infinite series
- From: Lew
- Print value of p from the infinite series
- Prev by Date: Re: Communicating from event handler to container
- Next by Date: Removing java operating files
- Previous by thread: Re: Print value of p from the infinite series
- Next by thread: Re: Print value of p from the infinite series
- Index(es):
Relevant Pages
|