I am coding this simple pi calculator for my Java class as a part of us learning about basic loops and it seems like everything is OK except the values printed for pi is infinity when it should be 3.14...something according to the number of iterations. I read that this could be maybe related to a double variable dividing by 0 and it's giving a weird infinity output instead of a normal Java runtime exception?
Here's my code:
package lab05;
public class Lab05 {
public static void main(String[] args) {
// Variable declarations
double pie = 3;
double savepie = 0;
double term = 0;
double savei = 0;
double sign = 1;
boolean isRangeFound = false;
int i;
// For loop
for (i=0; i <= 1000;) { // Only up to 1000 iterations before loop must end.
term = (sign * 4) / ((2*i) * (2*i+1) * (2*i+2));
pie = pie + term;
sign = (-1 * sign);
if (isRangeFound==false && (pie >=3.14159265 & pie < 3.14159266)) {
savepie = pie;
savei = i;
isRangeFound = true;
}
if (i == 200||i == 500||i == 1000) {
System.out.print("The value of \u03C0 is: ");
System.out.printf("%.10f",pie);
System.out.print(" when i = " + i);
System.out.println(" ");
}
i++;
}
// Final output statement
System.out.println ("The number of iterations to get to 3.14159265 is " + savei + ".");
System.out.printf("\n\u03C0 = %.10f",savepie);
System.out.println(" ");
}
}
Here's my output in Netbeans:
The value of π is: Infinity when i = 200
The value of π is: Infinity when i = 500
The value of π is: Infinity when i = 1000
The number of iterations to get to 3.14159265 is 0.0.
π = 0.0000000000
BUILD SUCCESSFUL (total time: 0 seconds)
Here's the link to the instructions that I should follow with a Visual Logic flowchart that I tried to follow to the T. Thanks. https://www.dropbox.com/s/2m26a32afedk9yu/Lab05%20Assignment%281%29.pdf?dl=0
You need to start your loop when i=1? The way you have it, when i=0, then term will be infinity (due to the divide-by-zero), and so pie will be infinity as well.