Python浮动比率

Python float to ratio(Python浮动比率)
本文介绍了Python浮动比率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

我使用 python 3.3

I using python 3.3

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

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

以及为什么它适用于 2.5

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

推荐答案

使用 fractions 模块 简化分数:

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)

来自 Fraction.limit_denominator() 函数一个>:

From the Fraction.limit_denominator() function:

查找并返回与 self 最接近且分母最多为 max_denominator 的 Fraction.此方法对于找到给定浮点数的有理逼近很有用

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'

因为浮点数表示为二进制小数的总和;1/5 只能通过将 1/8 + 1/16 + 1/128 + 更多的二进制分数相加来表示,以增加 2 的指数.

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浮动比率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)