問題描述
我有一個 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/10
的 int
底值(它不會產生浮點數).與浮點數不同,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 中管理大量數字的除法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!