如何在Python中管理巨数的划分? [英] How to manage division of huge numbers in Python?

查看:113
本文介绍了如何在Python中管理巨数的划分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个100位数的号码,我想把号码的所有数字放到一个列表中,以便我可以对它们执行操作。为此,我使用下面的代码:

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

面对的是,我得到了一个溢出错误,如太大的数字浮点数/整数。我甚至尝试使用下面的替代方案:

$ p $ number = int(number / 10)

如何将这个庞大的数字与整数类型的结果分开,即不是浮点数?

number / 10 会返回尝试返回一个 float 。然而,在Python中浮点值不能是任意大的,如果 number 很大,那么 OverflowError 将会是

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

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

为了解决这个限制, // 从两个整数中除去一个整数:

  number // 10 

这将返回 int number / 10 的底价(不会产生浮动)。与浮点数不同, int 值可以像Python 3中那样大(在内存限制内)。



<你现在可以分大数字。例如,在Python 3中:

 >>> 2 ** 3000/10 
OverflowError:浮点整数除法结果太大

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


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?

解决方案

In Python 3, number / 10 will return 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.

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

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).

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中管理巨数的划分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆