Check if a number is rational in Python, for a given fp accuracy

前端 未结 7 1149
迷失自我
迷失自我 2020-12-19 02:53

I would like to know a good way of checking if a number x is a rational (two integers n,m exist so that x=n/m) in python.

In Mathematica, this is done by the functio

7条回答
  •  春和景丽
    2020-12-19 03:25

    Python uses floating-point representation rather than rational numbers. Take a look at the standard library fractions module for some details about rational numbers.

    Observe, for example, this, to see why it goes wrong:

    >>> from fractions import Fraction
    >>> 1.1  # Uh oh.
    1.1000000000000001
    >>> Fraction(1.1)  # Will only work in >= Python 2.7, anyway.
    Fraction(2476979795053773, 2251799813685248)
    >>> Fraction(*1.1.as_integer_ratio())  # Python 2.6 compatible
    Fraction(2476979795053773, 2251799813685248)
    

    (Oh, you want to see a case where it works?)

    >>> Fraction('1.1')
    Fraction(11, 10)
    

提交回复
热议问题