if statements, for loops, doubles, functions Student approved
pi (π), the ratio of a circle's circumference to its diameter, is often written as 3.141592653. The decimal doesn't repeat, but you can estimate it using the Leibniz formula for pi:
Alternate adding and subtracting fractions with a
numerator of 4 and adenominator of the subsequent odd number, starting with 1:
pi = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) ...
The series is infinite - it goes on forever – and gets more precise with each additional term.
calculatePi
to use the Leibniz formula for pi. The int iterations
denotes how many terms we should add. Print the approximation after each iteration.4/13
). What do you get? class Calculator{
public static void main(String[] args){
int iterations = 11;
double pi = Calculator.calculatePi(iterations);
System.out.println(pi);
}
public static double calculatePi(int termsToAdd){
double pi = 0.0;
// Calculate pi, using the (4/1) - (4/3) + (4/5) ... series here
return pi;
}
}
1: 4
2: 2.666666666666667
3: 3.466666666666667
4: 2.8952380952380956
5: 3.3396825396825403
6: 2.9760461760461765
7: 3.2837384837384844
8: 3.017071817071818
9: 3.2523659347188767
10: 3.0418396189294032
11: 3.232315809405594