[英]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).我试图通过pi= 3 + (4/(2*3*4)) - (4/(4*5*6)) + (4/(6*7*8)) - …
(等等)。 However, my code (shown below) had 2 separate answers (3.1415926535900383 and 3.141592653590042) when:但是,我的代码(如下所示)在以下情况下有 2 个单独的答案(3.1415926535900383 和 3.141592653590042):
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.我认为是因为在 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.这是因为 float 在 python 中的方式。 If you do not have the digit before the decimal it gives 3 extra precision digits(from my trial).如果您没有小数点前的数字,它会提供 3 个额外的精度数字(来自我的试验)。 This changes the answer because when you start with 0, you get a different calculation altogether.这会改变答案,因为当您从 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.虽然浮点舍入会影响您的结果,但即使使用无限精度算术,您也会看到差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.