gpt4 book ai didi

python - float.as_integer_ratio() 的实现限制

转载 作者:太空狗 更新时间:2023-10-29 18:04:14 33 4
gpt4 key购买 nike

近日,有记者提到float.as_integer_ratio() ,Python 2.6 中的新增功能,指出典型的浮点实现本质上是实数的有理逼近。出于好奇,我不得不尝试 π:

>>> float.as_integer_ratio(math.pi);
(884279719003555L, 281474976710656L)

我有点惊讶没有看到更多 accurate结果归因于 Arima ,:

(428224593349304L, 136308121570117L)

例如,这段代码:

#! /usr/bin/env python
from decimal import *
getcontext().prec = 36
print "python: ",Decimal(884279719003555) / Decimal(281474976710656)
print "Arima: ",Decimal(428224593349304) / Decimal(136308121570117)
print "Wiki: 3.14159265358979323846264338327950288"

产生这个输出:

python:  3.14159265358979311599796346854418516Arima:   3.14159265358979323846264338327569743Wiki:    3.14159265358979323846264338327950288

当然,鉴于 64 位 float 提供的精度,结果是正确的,但这让我想问:我如何才能更多地了解 as_integer_ratio() 的实现限制?感谢您的指导。

附加链接:Stern-Brocot treePython source .

最佳答案

使用

可以得到更好的近似值
fractions.Fraction.from_float(math.pi).limit_denominator()

可能从 3.0 版开始包含分数。但是,math.pi 没有足够的精度返回 30 位近似值。

关于python - float.as_integer_ratio() 的实现限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076290/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com