使用 Python 计算精确分数
我没有看到以下代码所期望的数学结果,我相信它应该产生谐波级数:
from fractions import Fraction
def sum_fracs(n):
if n == 1:
return 1
return 1/n + sum_fracs(n - 1)
for n in range(1, 6):
print(sum_fracs(n).as_integer_ratio())
for n in range(1, 6):
print(Fraction(sum_fracs(n)))
输出:
(1, 1)
(3, 2)
(8256599316845909, 4503599627370496)
(2345624805922133, 1125899906842624)
(1285402393645329, 562949953421312)
1
3/2
8256599316845909/4503599627370496
2345624805922133/1125899906842624
1285402393645329/562949953421312
两种方法都没有达到
1
3/2
11/6
25/12
137/60
我的预期。我知道浮点数可能有舍入误差,但我希望这种基本的东西在 Python 中是可能的。
非常感谢任何帮助。
I'm not seeing the mathematical results I'm expecting from the following code, which I believe should produce the Harmonic Series:
from fractions import Fraction
def sum_fracs(n):
if n == 1:
return 1
return 1/n + sum_fracs(n - 1)
for n in range(1, 6):
print(sum_fracs(n).as_integer_ratio())
for n in range(1, 6):
print(Fraction(sum_fracs(n)))
Output:
(1, 1)
(3, 2)
(8256599316845909, 4503599627370496)
(2345624805922133, 1125899906842624)
(1285402393645329, 562949953421312)
1
3/2
8256599316845909/4503599627370496
2345624805922133/1125899906842624
1285402393645329/562949953421312
Neither approach gives
1
3/2
11/6
25/12
137/60
as I was hoping. I know floats can have rounding errors, but I would hope that something this basic would be possible in Python.
Any help much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您运行
Fraction(x)
,其中x
是浮点数。这已经太晚了,你已经失去了精度,所以你的分数的精度与浮点数的精度一样好。在函数中使用
Fraction
:输出:
NB。
fraction
文档中清楚地说明了这一点< /em>You run
Fraction(x)
wherex
is a float. This is too late, you already lost precision, so your fraction's precision is as good as that of the float.Use
Fraction
in the function:output:
NB. this is clearly stated in the
fraction
documentation