本文介绍了float.as_integer_ratio()的实现限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,一名通讯员提到 float.as_integer_ratio() ,Python 2.6中的新增功能,指出典型的浮点实现本质上是实数的有理近似.出于好奇,我不得不尝试π:

Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π:

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

由于有马,:

(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.14159265358979311599796346854418516
Arima:   3.14159265358979323846264338327569743
Wiki:    3.14159265358979323846264338327950288

当然,鉴于64位浮点数提供的精度,结果是正确的,但它使我问:如何找到有关as_integer_ratio()的实现限制的更多信息?感谢您的指导.

Certainly, the result is correct given the precision afforded by 64-bit floating-point numbers, but it leads me to ask: How can I find out more about the implementation limitations of as_integer_ratio()? Thanks for any guidance.

其他链接:斯特恩-布罗科树 Python来源.

推荐答案

仅在分母中考虑2的幂..这(可能)是更好的算法.

这篇关于float.as_integer_ratio()的实现限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:57