{JAVA} Calculating PI without using class.math

ECSD

Honorable
Aug 17, 2012
4
0
10,510
Is it possible to calculate the Number PI without using the java class math?

I found this formula to calculate PI.

scaled.php


I think i need some int arrays to save the numbers but actually i'm stumped.

Has anyone a hint?
 

Sunius

Distinguished
Dec 19, 2010
390
0
19,060
That's not formula to calculate PI.. That's a formula for arcsine.

6f5daaa0b0d680ce1ee13669c31ce9ae.png


Shouldn't be that hard
Code:
double Pi = 4;
bool plus = 0;
for (int i = 3; i < 10000000; i += 2)
{
    if (plus)
    {
        Pi += 4.0 / i;
    }
    else
    {
        Pi -= 4.0 / i;
    }
    plus = !plus;
 }
 

Sunius

Distinguished
Dec 19, 2010
390
0
19,060
Does it matter? It would work on many languages. I tested it using Visual C++ compiler. I'm sure you can convert it to Java without any problems.
 

randomizer

Distinguished
It's a flag which determines whether or not to do an add operation or a subtract operation, and it is flipped* each time either is performed so that the two alternate. For Java you'd have to initialise the boolean to false, not 0.

*The ! inverts the boolean result of whatever follows it. So if "plus" is true, it will return false and vice versa.
 

ECSD

Honorable
Aug 17, 2012
4
0
10,510
Thanks. Should "i" be also a variable?
Because in Java you can't divide i if it is not declared as a variable.
 

randomizer

Distinguished
It is already declared and initialised at the start of the for loop, and its scope is restricted to the loop as well.

I'm guessing this task is for some homework. I can't think of any common reason to want to manually calculate pi except because you are told that you must.
 

Sunius

Distinguished
Dec 19, 2010
390
0
19,060
I'm not really familiar with Java syntax, but from what randomizer said bool plus = 0 equivalent in Java should be:

Code:
boolean plus = false;

And as for i, it's declared in the loop at line 3:
Code:
int i = 0;

Finally, operator ! flips the boolean value, if it was true, it becomes false, and if it was false, it becomes true.
 
G

Guest

Guest
Hi,

I was given the same task as ECSD, using the arcsine formula from the first post. Further info: when x=0.5 --> 6*arcsin(x) = Pi . That's how the formula might be incorporated. I'm completely new to Programming and I'm confused as to how to calculate to a power without using the Math.Class... I have the instructions to not use the Math.Class and to save the first 10000 digits of Pi in int-arrays.. any advice would be much appreciated :)
 
G

Guest

Guest
no, other than the 10000 digits of Pi there's nothing specifically specified..
 

Sunius

Distinguished
Dec 19, 2010
390
0
19,060
I suppose you'll have to write your own operators: +, *, /, which take arrays as operands instead of numbers. That's the only way I see it would work.