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

前端 未结 7 1159
迷失自我
迷失自我 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:20

    In python >= 2.6 there is a as_integer_ratio method on floats:

    >>> a = 6.75
    >>> a.as_integer_ratio()
    (27, 4)
    >>> import math
    >>> math.pi.as_integer_ratio()
    (884279719003555, 281474976710656)
    

    However, due to the way floats are defined in programming languages there are no irrational numbers.

提交回复
热议问题