Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
通过执行以下操作,您将离您想要的位置足够近:
def sumof3(n):
n = float((n-1)/3)
return int((n/2)*(6+3*(n-1)))
或者如果你想说得更准确些:
def sumof3(n):
n = float((n-1)/3)
return float((n/2)*(6+3*(n-1)))
这是round-off error的一个例子:
通过执行以下操作,您将离您想要的位置足够近:
或者如果你想说得更准确些:
Python有任意精度的整数,但有标准的有限(双)精度浮点。在python3中,两个整数除以
/
产生一个浮点,这意味着但是如果我们纯粹使用
//
处理整数,我们会得到:在您的代码中,
(n-1)/3
和(n/2)
都将产生浮点输出,这意味着您只有大约18位精度。如果我们将你的函数修改为纯整数:然后我们得到低值的一致性:
但在高值时,我们保持精度:
[这里我们可以重新排序以确保不会丢失任何分数数据,但有时我发现^{} 模块也很方便。]
对
int
来说太大了对我来说是指纹
让我哑巴!误解了这个问题!对不起的!你知道吗
相关问题 更多 >
编程相关推荐