简体   繁体   中英

Why is there a difference between starting with a "0" and "3" for approx

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM