Apple, cherry, or pumpkin? Download

Christina Cacioppo

if statements, for loops, doubles, functions Student approved


Introduction

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 a denominator 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.


Task

  1. First, edit the function calculatePi to use the Leibniz formula for pi. The parameter int iterations denotes how many terms we should add. Print the approximation after each iteration.
  2. Next, approximate pi by cycling through the loop 7 times (that is, until the last addition is 4/13). What do you get?

  3. What's the difference in the approxiamtion you get from running the loop 20 times versus 10 time? (You should only have to make one change to your program to calculate this!)


Starter code

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;
	}
}

Expected output

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

One solution


Hints



Useful tools to solve the problem


Related links