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

How to manage division of huge numbers in Python?(如何在 Python 中管理大量数字的除法?)
本文介绍了如何在 Python 中管理大量数字的除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 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...

这篇关于如何在 Python 中管理大量数字的除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)