简体   繁体   English

如何高精度地将非常长的小数转换为分数并返回

[英]How to convert incredibly long decimals to fractions and back with high precision

I'm trying to convert very large integers to decimals, then convert those decimals to Fractions, and then convert the Fraction back to a decimal.我正在尝试将非常大的整数转换为小数,然后将这些小数转换为分数,然后将分数转换回小数。 I'm using the fractions and decimal packages to try and avoid floating point imprecision, however the accuracy still tapers off rather quickly.我正在使用分数和小数包来尝试避免浮点不精确,但精度仍然很快下降。 Is there any way to fix this / other ways of doing this?有什么办法可以解决这个问题/其他方法吗?


import fractions
import decimal


def convert(exampleInt):
    power_of_10 = len(str(exampleInt))
    decimal.getcontext().prec = 10000
    exampleDecimal = decimal.Decimal(exampleInt) / (decimal.Decimal(10) ** power_of_10)
    exampleFraction = fractions.Fraction(str(exampleDecimal)).limit_denominator()
    backToDecimal = exampleFraction.numerator / decimal.Decimal(exampleFraction.denominator)
    print(f"backToDecimal: {backToDecimal}")


convert(34163457536856478543908582348965743529867234957893246783427568734742390675934285342)

Which outputs: .341634575369123189552597490138153768602695082851231192155069838....输出:.341634575369123189552597490138153768602695082851231192155069838....

It's because of calling the limit_denominator() .这是因为调用了limit_denominator() Also it's quite inefficient to convert using an intermediate string.使用中间字符串进行转换的效率也很低。

Use Decimal.as_integer_ratio() like the following.使用Decimal.as_integer_ratio()如下所示。

import fractions
import decimal

decimal.getcontext().prec = 100

d = decimal.Decimal(34163457536856478543908582348965743529867234957893246783427568734742390675934285342)
d = d / 10**(d.adjusted() + 1)

f = fractions.Fraction(*d.as_integer_ratio())
d2 = decimal.Decimal(f.numerator) / f.denominator
assert(d2 == d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM