如何将十进制数转换为分数? [英] How to convert a decimal number into fraction?

查看:264
本文介绍了如何将十进制数转换为分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Python中以最低的形式将小数转换为分数。

I was wondering how to convert a decimal into a fraction in its lowest form in Python.

例如:

0.25  -> 1/4
0.5   -> 1/2
1.25  -> 5/4
3     -> 3/1


推荐答案

您有两个选择:


  1. 使用 float.as_integer_ratio()

>>> (0.25).as_integer_ratio()
(1, 4)

(自Python 3.6起) ,您可以十进制进行相同操作.Decimal()对象。)

(as of Python 3.6, you can do the same with a decimal.Decimal() object.)

使用 fractions.Fraction()类型

>>> from fractions import Fraction
>>> Fraction(0.25)
Fraction(1, 4)


后者具有非常有用的 str()转换:

The latter has a very helpful str() conversion:

>>> str(Fraction(0.25))
'1/4'
>>> print Fraction(0.25)
1/4

由于浮点值可能不精确,可能以怪异分数结尾;使用 <$ c来限制分母以某种程度上简化分数$ c> Fraction.limit_denominator()

Because floating point values can be imprecise, you can end up with 'weird' fractions; limit the denominator to 'simplify' the fraction somewhat, with Fraction.limit_denominator():

>>> Fraction(0.185)
Fraction(3332663724254167, 18014398509481984)
>>> Fraction(0.185).limit_denominator()
Fraction(37, 200)

如果仍使用Python 2.6,则 Fraction()尚不支持直接传递 float ,但是您可以将以上两种技术结合起来:

If you are using Python 2.6 still, then Fraction() doesn't yet support passing in a float directly, but you can combine the two techniques above into:

Fraction(*0.25.as_integer_ratio())

或者您也可以使用 Fraction.from_float()类方法

Or you can just use the Fraction.from_float() class method:

Fraction.from_float(0.25)

基本上做同样的事情,例如取整数比率元组并将其作为两个单独的参数传递。

which essentially does the same thing, e.g. take the integer ratio tuple and pass that in as two separate arguments.

还有一个带有示例值的小演示:

And a small demo with your sample values:

>>> for f in (0.25, 0.5, 1.25, 3.0):
...     print f.as_integer_ratio()
...     print repr(Fraction(f)), Fraction(f)
... 
(1, 4)
Fraction(1, 4) 1/4
(1, 2)
Fraction(1, 2) 1/2
(5, 4)
Fraction(5, 4) 5/4
(3, 1)
Fraction(3, 1) 3

分数模块和 float.as_integer_ratio()方法是Python 2.6中的新功能。

Both the fractions module and the float.as_integer_ratio() method are new in Python 2.6.

这篇关于如何将十进制数转换为分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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