检查了一些在Python是理性的 [英] Check if a number is rational in Python

查看:94
本文介绍了检查了一些在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.

在数学,这是由函数完成

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?

推荐答案

在蟒蛇> = 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)

然而,由于路上浮标在编程语言中定义的没有无理数

这篇关于检查了一些在Python是理性的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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