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

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

    The problem with real numbers in programming languages is that they are usually defined as functions returning a finite representation given an accuracy (eg. a function which takes n as an argument and returns a floating point number within 2^-n accuracy).

    You can definitely turn a rational/integer into a real, but even comparing reals for equality is undecidable (it is essentially the halting problem).

    You cannot tell whether a real number x is rational: even in mathematics, it is usually difficult, since you have to find p and q such that x = p/q, and this is often non constructive.

    However, given an accuracy window, you can find the "best" rational approximation for this accuracy using for instance continuous fraction expansion. I believe that is essentially what mathematica does. But in your exemple, 6.75 is already rational. Try with Pi instead.

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