-1

I am really having trouble getting started on this assignment and would really appreciate some help as a newbie!

We need to write a program called PiApproximator that approximates the mathematical constant π by summing a finite number of terms in a series for it.

The series we are using is pi=4-4/3+4/5-4/7 etc..

2 Answers2

1

Since you said you just want to get started on solving this I'll break down the components of the question

  1. While function statement; the loop needs to continue as long as the added term is greater than 1e-6, so you'll need a variable for whatever variable is added for that loop.
  2. You need a counter for the number of loops; both for an output and in order to control whether the term will be added or subtracted from the total (hint: a % is useful here)
  3. You will need a way to change the next number in the series; a good way of doing this would be to link it to the loop counter ie series_num = 4/(3 + 2 * loop)

I've tried to give as much info as possible without straight out giving you the answer but let me know if you need any more help

Ponyboy
  • 76
  • 5
0

Your code has the right ideas. One solution would be to make the different parts simpler

# pi ~ + 4/1 - 4/3 + 4/5 - 4/7 ...
pi, x, d = 0, 1, 1
while 4 / d > 1e-6:
    pi += 4 / d * x
    d  += 2
    x  *= -1
print(f'Approximation of pi is {pi} [in {(d+1) // 2} iterations]')

Output

Approximation of pi is 3.141592153589724 [in 2000001 iterations]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32