如何在 Python 中管理大量数字的除法?

2022-01-09 00:00:00 python floating-point integer division

问题描述

我有一个 100 位数字,我试图将数字的所有数字放入一个列表中,以便对它们执行操作.为此,我使用以下代码:

I have a 100 digit number and I am trying to put all the digits of the number into a list, so that I can perform operations on them. To do this, I am using the following code:

for x in range (0, 1000):
   list[x] = number % 10
   number = number / 10

但我面临的问题是我收到了一个溢出错误,比如浮点数/整数太大.我什至尝试使用以下替代方法

But the problem I am facing is that I am getting an overflow error something like too large number float/integer. I even tried using following alternative

number = int (number / 10)

如何将这个巨大的数字除以整数类型的结果,即没有浮点数?

How can I divide this huge number with the result back in integer type, that is no floats?


解决方案

在 Python 3 中,number/10 将尝试返回 float.但是,浮点值在 Python 中不能任意大,如果 number 很大,则会引发 OverflowError.

In Python 3, number / 10 will try to return a float. However, floating point values can't be of arbitrarily large size in Python and if number is large an OverflowError will be raised.

您可以使用 sys 模块找到 Python 浮点值可以在您的系统上使用的最大值:

You can find the maximum that Python floating point values can take on your system using the sys module:

>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

要绕过此限制,请改为使用 // 从两个整数的除法中取回一个整数:

To get around this limitation, instead use // to get an integer back from the division of the two integers:

number // 10

这将返回 number/10int 底值(它不会产生浮点数).与浮点数不同,int 值可以根据您在 Python 3 中所需的大小(在内存限制内).

This will return the int floor value of number / 10 (it does not produce a float). Unlike floats, int values can be as large as you need them to be in Python 3 (within memory limits).

您现在可以划分大数.例如,在 Python 3 中:

You can now divide the large numbers. For instance, in Python 3:

>>> 2**3000 / 10
OverflowError: integer division result too large for a float

>>> 2**3000 // 10
123023192216111717693155881327...

相关文章