Python中的浮点数到分数转换 [英] Float to Fraction conversion in Python

查看:1132
本文介绍了Python中的浮点数到分数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3.52中进行从浮点类型到分数类型转换的主题的练习时,我发现了两种不同转换方式之间的区别.

While doing exercise on the topic of float type to Fraction type conversion in Python 3.52, I found the difference between the two different ways of conversion.

第一种方法是:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(*x.as_integer_ratio())
>>> print(f)
2709702426188841/2199023255552      #Answer

第二种方法是:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(str(x))
>>> print(f)
123223/100                          #Answer

我想知道这两个不同答案背后的原因吗?抱歉,如果这是一个愚蠢的问题,我是编程和Python的新手.

I want to know the reason behind these two different answers? Sorry if this is a stupid question , I am new to programming and Python.

我找到了一种方法,可以将第一种方法获得的不精确分数转换为limit_denominator方法的精确度:

Edited: I found a way to convert inaccurate fraction obtained by first method to accurate by limit_denominator method:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(*x.as_integer_ratio())
>>> f = f.limit_denominator(100)     
>>> print(f)
123223/100

推荐答案

再次是因为浮点数不是存储在base-10(十进制)中,而是存储在base-2(二进制)中.

Yet again it's because floating point numbers aren't stored in base-10 (decimal), but in base-2 (binary).

以10为底的有限长度数字可能是以2为底的重复小数.而且由于浮点数是固定大小的,因此重复的小数点会被截断,从而导致不准确.

A number that is finite length in base-10 might be a repeating decimal in base-2. And because floats are a fixed size, that repeating decimal gets truncated, resulting in inaccuracies.

当您使用as_integer_ratio表示基数为2的重复小数时,由于基数10到基数2的转换略有误差,您会得到一些愚蠢的分数.如果将这两个数字相除,则该值将非常接近原始数字.

When you use as_integer_ratio for a number that's a repeating decimal in base-2, you will get you a somewhat silly fraction as a result of the slight inaccuracies in the base-10 to base-2 conversion. If you divide those two numbers, the value will be very close to to your original number.

例如,虽然以10为底的1/10 = 0.1,并且不是重复的小数,但实际上是以2为底的重复小数.就像以10为底的1/3 = 0.333 ...

For instance, while 1/10 = 0.1 in base-10 and is not a repeating decimal, it is in fact a repeating decimal in base-2. Just like 1/3 = 0.333... in base-10.

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

如果Python的输出是准确的,则即使在提示符下仅输入0.1,您也将看到1.00000 ... 01之类的输出,从而看到了这一点.但是在一般情况下,Python会掩盖这种不准确之处,从而导致混乱.

If Python's output was exact, you would see this even when you enter just 0.1 in the prompt, by getting something like 1.00000...01 as the output. But Python hides this inaccuracy from you in the general case, leading to confusion.

这篇关于Python中的浮点数到分数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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