Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

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

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 function Rationalize[6.75] : 27/4

I assume this question has an answer for a given accuracy. Is there a common algorithm of obtaining these two integers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...