Python浮动到比例 [英] Python float to ratio

查看:350
本文介绍了Python浮动到比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试得到变量的比例,并得到意想不到的结果。有人可以解释一下吗?

 >>>值= 3.2 
>>>比率= value.as_integer_ratio()
>>>比率
(3602879701896397,1125899906842624)
>>>比率[0] /比率[1]
3.2

我使用python 3.3



但是我认为(16,5)是更好的解决方案

为什么它正确 2.5

 >> >值= 2.5 
>>> value.as_integer_ratio()
(5,2)


解决方案

使用 分数模块来简化分数:

 >>> from fractions进口分数
>>>分数(3.2)
分数(3602879701896397,1125899906842624)
>>>分数(3.2).limit_denominator()
分数(16,5)

一个href =http://docs.python.org/2/library/fractions.html#fractions.Fraction.limit_denominator> Fraction.limit_denominator() a>:b
$ b


查找并返回最近的分数,其分母最多为max_denominator。这个方法对寻找给定浮点数的有理逼近很有用。浮点数的精度有限,不能表示很多数字。 准确;你看到的是一个圆整的表示,但实际的数字是:

 >>>格式(3.2,'.50f')
'3.20000000000000017763568394002504646778106689453125'

因为浮点数被表示为二进制分数的总和; 1/5只能通过将增加1/8 + 1/16 + 1/128以上的二进制分数来表示,以增加两个指数。

I try get ration of variable and get unexpected result. Can somebody explain this?

>>> value = 3.2
>>> ratios = value.as_integer_ratio()
>>> ratios
(3602879701896397, 1125899906842624)
>>> ratios[0] / ratios[1]
3.2

I using python 3.3

But I think that (16, 5) is much better solution

And why it correct for 2.5

>>> value = 2.5
>>> value.as_integer_ratio()
(5, 2)

解决方案

Use the fractions module to simplify fractions:

>>> from fractions import Fraction
>>> Fraction(3.2)
Fraction(3602879701896397, 1125899906842624)
>>> Fraction(3.2).limit_denominator()
Fraction(16, 5)

From the Fraction.limit_denominator() function:

Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number

Floating point numbers are limited in precision and cannot represent many numbers exactly; what you see is a rounded representation, but the real number is:

>>> format(3.2, '.50f')
'3.20000000000000017763568394002504646778106689453125'

because a floating point number is represented as a sum of binary fractions; 1/5 can only be represented by adding up 1/8 + 1/16 + 1/128 + more binary fractions for increasing exponents of two.

这篇关于Python浮动到比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆