Python float to ratio

前端 未结 2 1672
说谎
说谎 2020-12-10 07:08

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

>>> value = 3.2
>>> ratios = value.as_integer_ratio()
&g         


        
相关标签:
2条回答
  • 2020-12-10 07:16

    It's not 16/5 because 3.2 isn't 3.2 exactly... it's a floating point rough approximation of it... eg: 3.20000000000000017764

    0 讨论(0)
  • 2020-12-10 07:36

    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.

    0 讨论(0)
提交回复
热议问题