Python3 停止对大浮点数进行除法

Python3 Stop division for large floats

我正在划分非常大的整数,可以说最大为 1kb 的整数,我 运行 已经分为 2 个问题。

OverflowError: integer division result too large for a float

或者浮点数四舍五入为一些数字,当我尝试乘回去时,我得到的数字略有不同。

在 python 中有什么方法可以防止分割小数点后超过 20 位的浮点数吗?

smallest_floats = []

n1 = int(input())
n2 = int(input())

while n2 != 1:
  smallest_floats.append(str(n1/n2))
     n2 -= 1
print(min(smallest_floats, key=len))

我认为可能的解决方案是以某种方式断言除法或:

len(s.split(".")[-1]) > 20

对于没有精度损失的有理数运算,您可以使用 fractions package 中的 fractions.Fraction class。您可以除以另一个有理数,然后再乘以它,以获得与开始时完全相同的有理数。

>>> from fractions import Fraction
>>> n1 = Fraction(large_numerator, denominator)
>>> n2 = n1 / some_rational_number
>>> assert n1 == n2 * some_rational_number

导入 decimal 模块 (https://docs.python.org/2/library/decimal.html) 它具有任意精度

您可以使用

增加显示的十进制数字
>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573') 100 decimal digits

how can i show an irrational number to 100 decimal places in python?