Python3停止划分大浮点数

时间:2017-01-15 23:09:46

标签: python python-3.x math division integer-division

我正在划分非常大的整数,所以说到1kb整数,我已经遇到了2个问题。

  

OverflowError:对于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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

导入具有严格精确度的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?

相关问题