Print value of p from the infinite series



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>

.



Relevant Pages

  • Re: Get/Set Property for Array
    ... "Mr. Arnold" wrote in message ... private Arraylist _jpmsft = new Arraylist; ... The ArrayList has been dead since VS 2005, when I just instantiated an ArrayListobject in VS 2008 from the System.Collections? ... What if I wanted to have an int that has a count of how many objects there were in the list followed by the objects, then another int telling how many objects followed by its objects, casting back on the other side as I walked the ArrayList. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Get/Set Property for Array
    ... Studio 2005. ... The ArrayList has been dead since VS 2005, ... What if I wanted to have an int that has a count of how many objects ... In the first instance you can use a more specific type if for example both ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Thou shalt have no other gods before the ANSI C standard
    ... Hint: I use a version of GCC with 16-bit int every day. ... dead branch, either. ...
    (sci.crypt)
  • Re: Character Constants
    ... Undefined behavior. ... You're dead. ... defined int constant is outside the range of char and an implementation ...
    (comp.lang.c)