Help with understanding the following commented codes!

• April 2nd, 2011, 02:58 PM
u-will-neva-no
Help with understanding the following commented codes!
Hello, the code below is an extract from a small program which lets the user choose the number of iterations (for an approximation of PI/4). The program works, however i do not understand how it is working. Please help me understand the following lines...

Code Java:

for (int i=0; i<iteration; i++) { //i understand this
double sum = 1.0/(2.0*(i) + 1.0); //just the formula
if (positive) //do not understand this!!

output += sum; //same as output = output + sum
else
output -= sum; // same as output = output - sum
positive = !positive; // not sure how this is helping with the program!

Thanks!
• April 2nd, 2011, 03:38 PM
Valen007
Re: Help with understanding the following commented codes!
Hello.

'Output' is the result. Here we have summation of elements that approximate PI/4.These series approximate Pi/4 with sum of elements with alternating signs.

If 'positive' is true then we add an element to 'output',
if 'positive' is false then we subtract the an element from 'output'.

Because the signs are alternating we must change the 'positive' value every time.
That is what we do with

Code :

positive = !positive;

If we choose iterations to be a big number, then we get a good approximation with this code. I added some definitions and print the output ,

Code :

package mypack;

public class Main {

public static void main(String[] args) {
int iteration=1000;
double output=0;
boolean positive=true;

for (int i=0; i<iteration; i++) {
double sum = 1.0/(2.0*(i) + 1.0);

if (positive) //if positive we add otherwise we subtract
output += sum;
else
output -= sum;

positive = !positive; // changing the sign of the next summation
}

System.out.println("Approximated Pi/4="+output);

}

}

Here the number of iterations was set for 1000, and if we run the code , we get
the result printed

Code :

Approximated Pi/4=0.7851481634599485

which is pretty close to real PI/4=0.785398163

Hope it helped,
Valentin
• April 2nd, 2011, 04:26 PM
u-will-neva-no
Re: Help with understanding the following commented codes!
Thankyou very much Valetin, now i understand!