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

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

    Any number with a finite decimal expansion is a rational number. You could always solve for instance

    5.195181354985216
    

    by saying that it corresponds to

    5195181354985216 / 1000000000000000
    

    So since floats and doubles have finite precision they're all rationals.

提交回复
热议问题