Print value of p from the infinite series
- From: Lea0x.Diz@xxxxxxxxx
- Date: 26 Feb 2007 09:01:12 -0800
Hi, new here.
I'm trying to print a table that shows how many terms needed to
accomplished 3.14, 3.141, 3.1415, 3.14159.
But, dead end with weird logic-error (at least for me, right now).
Here is how, suppose the output should something like:
<code>
full: p: flag: p in int: counter:
4.000000 4.000 true 4000 1
2.666667 2.667 false 2666 2
3.466667 3.467 true 3466 3
....
<snipped>
....
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
It tooks 1688 terms to accomplished the task.
</code>
But hey, isn't that term at 1686 should terminate the for-loop, and
the `p in int' should yield 3141, but it return 3140 and take another
2 extra loops to complete, weird, huh?
Perhaps, I just missed something that I shouldn't.
Anybody known better algorithm, fix?
Here is the code:
<code>
final double four = 4.0;
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
}
System.out.printf("It tooks %d terms to accomplished the task.\n",
count);
</code>
.
- Follow-Ups:
- Prev by Date: Re: How do you consistently repaint a JComponent?
- Next by Date: Re: Checking input for letters
- Previous by thread: Serialization problem
- Next by thread: Re: Print value of p from the infinite series
- Index(es):
Relevant Pages
|