Here is the problem that I am trying to solve:
Write a program that calculates the value of pi using the Gregory series. The input to the program will be a decimal value called limit. The program shall proceed to calculate the value of pi by summing up the terms of the series, but only until such time that the value of the term being summed becomes less than or equal to the value of limit, at which point the program terminates the summation. Thus, the last term of the series that is added to the sum is the first term whose value is less than or equal to the value of limit. The program then prints out the calculated value of pi at that point, as well as the actual number of terms that were summed up by the calculation.
Here is what the output should look like:
Input Limit: 0.005
Calculated Value of PI: 3.1659792728432157
No. of Terms Summed: 41
My code:
class Scratch {
public static void main(String[] args) {
int k = 1;
double pi = 0.0;
for (int term = 1; term < 50000; term++){
double currVal = 0.0;
if (term % 2 == 0) {
currVal = (double) -4 / k;
} else {
currVal = (double) 4 / k;
}
pi = pi + currVal;
if(((double)4/k) < 0.005){
System.out.println(pi);
System.out.println(term);
break;
}
k = k + 2;
}
}
}
My code's output:
3.144086415298761
401
Please let me know where did I go wrong? Any advise is greatly appreciated.