-1

I was attempting an approximated value of pi through the formula of pi= 3 + (4/(2*3*4)) - (4/(4*5*6)) + (4/(6*7*8)) - … (and so on). However, my code (shown below) had 2 separate answers (3.1415926535900383 and 3.141592653590042) when:

  1. approx variable started with "0" and "3" respectively
  2. n=10000

Does anyone know why?

def approximate_pi(n):
    approx=0
    deno=2
    if n == 1:
        return 3
    for x in range(n-1):
        if x%2:
            approx -= 4/((deno)*(deno+1)*(deno+2))
        else:
            approx += 4/((deno)*(deno+1)*(deno+2))
        deno+=2
    return approx+3

and

def approximate_pi(n):
    approx=3
    deno=2
    if n == 1:
        return 3
    for x in range(n-1):
        if x%2:
            approx -= 4/((deno)*(deno+1)*(deno+2))
        else:
            approx += 4/((deno)*(deno+1)*(deno+2))
        deno+=2
    return approx
jww
  • 97,681
  • 90
  • 411
  • 885
  • @tripleee - I thought this had some close votes due to duplicates. Did something happen to them? – jww Nov 12 '18 at 09:33

3 Answers3

0

I think is because you can't have exact float numbers in pc. More info you can get here: Why can't decimal numbers be represented exactly in binary?

ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
0

It is because of the way float is in python. If you do not have the digit before the decimal it gives 3 extra precision digits(from my trial). This changes the answer because when you start with 0, you get a different calculation altogether.

Knl_Kolhe
  • 191
  • 8
0

An approximation algorithm approximates. Neither number is the true value of π. Your two versions start at different starting points, so why are you surprised that they give you slightly different approximations? What matters is that the longer you run them, the further they will both converge to the true value.

Note that this is not an artifact of the finite-precision representation of floats. While floating point rounding will affect your results, you would see differences even with unlimited precision arithmetic.

alexis
  • 48,685
  • 16
  • 101
  • 161