問題描述
我嘗試獲取變量的比例并得到意想不到的結(jié)果.有人可以解釋一下嗎?
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
但我認(rèn)為 (16, 5)
是更好的解決方案
But I think that (16, 5)
is much better solution
以及為什么它適用于 2.5
>>> value = 2.5
>>> value.as_integer_ratio()
(5, 2)
推薦答案
使用 fractions
模塊 簡(jiǎn)化分?jǐn)?shù):
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)
來(lái)自 Fraction.limit_denominator()
函數(shù)一個(gè)>:
From the Fraction.limit_denominator()
function:
查找并返回與 self
最接近且分母最多為 max_denominator 的 Fraction
.此方法對(duì)于找到給定浮點(diǎn)數(shù)的有理逼近很有用
Finds and returns the closest
Fraction
toself
that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number
浮點(diǎn)數(shù)精度有限,不能精確表示;你看到的是一個(gè)四舍五入的表示,但實(shí)數(shù)是:
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'
因?yàn)楦↑c(diǎn)數(shù)表示為二進(jìn)制小數(shù)的總和;1/5 只能通過將 1/8 + 1/16 + 1/128 + 更多的二進(jìn)制分?jǐn)?shù)相加來(lái)表示,以增加 2 的指數(shù).
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.
這篇關(guān)于Python浮動(dòng)比率的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!