对于给定的fp精度,检查数字在Python中是否合理 [英] Check if a number is rational in Python, for a given fp accuracy

查看:66
本文介绍了对于给定的fp精度,检查数字在Python中是否合理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一种检查python中数字x是否是有理数(存在两个整数n,m以便x = n/m)的好方法.

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.

在Mathematica中,这是通过函数Rationalize[6.75]:27/4

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?

推荐答案

在python> = 2.6中,有一个 as_integer_ratio 浮点数的方法:

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.

这篇关于对于给定的fp精度,检查数字在Python中是否合理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆