级数的和。这个Python代码有什么问题?

2024-09-27 00:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,求出给定n下所有3的倍数之和。 到目前为止,我提出了这个解决方案(使用算术级数的公式):

def sumof3(n):
    n = int((n-1)/3)
    return int((n/2)*(6+3*(n-1)))

它工作得很好,但由于某些原因,它开始失败,大量的数字。例如,n=232471924 返回值是9007199280122284,而应该是9007199280122283。你知道吗

有人能告诉我哪里有虫子吗?你知道吗


Tags: 程序returndef原因数字解决方案公式int
3条回答

这是round-off error的一个例子:

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)))

Python有任意精度的整数,但有标准的有限(双)精度浮点。在python3中,两个整数除以/产生一个浮点,这意味着

>>> 10**50/10**25
1e+25
>>> int(10**50/10**25)
10000000000000000905969664

但是如果我们纯粹使用//处理整数,我们会得到:

>>> 10**50//10**25
10000000000000000000000000

在您的代码中,(n-1)/3(n/2)都将产生浮点输出,这意味着您只有大约18位精度。如果我们将你的函数修改为纯整数:

def sumof3b(n):
    n = (n-1)//3
    return (6+3*(n-1))*n//2

然后我们得到低值的一致性:

>>> all(sumof3(n) == sumof3b(n) for n in range(10**7))
True

但在高值时,我们保持精度:

>>> n = 232471924
>>> sumof3(n) # bad
9007199280122284
>>> sumof3b(n) # good
9007199280122283

[这里我们可以重新排序以确保不会丢失任何分数数据,但有时我发现^{}模块也很方便。]

int来说太大了

import sys
print int(sys.maxint)
print int(sys.maxint*2)

对我来说是指纹

2147483647
-2

让我哑巴!误解了这个问题!对不起的!你知道吗

相关问题 更多 >

    热门问题