如何在 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 中管理大量数字的除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)