Windows上的“溢出错误:Python int太大而无法转换为C long”,但不是mac
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38314118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"OverflowError: Python int too large to convert to C long" on windows but not mac
提问by packybear
I am running the exact same code on both windows and mac, with python 3.5 64 bit.
我在 windows 和 mac 上运行完全相同的代码,python 3.5 64 位。
On windows, it looks like this:
在 Windows 上,它看起来像这样:
>>> import numpy as np
>>> preds = np.zeros((1, 3), dtype=int)
>>> p = [6802256107, 5017549029, 3745804973]
>>> preds[0] = p
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
preds[0] = p
OverflowError: Python int too large to convert to C long
However, this code works fine on my mac. Could anyone help explain why or give a solution for the code on windows? Thanks so much!
但是,此代码在我的 mac 上运行良好。任何人都可以帮助解释原因或为 Windows 上的代码提供解决方案吗?非常感谢!
采纳答案by Moses Koledoye
You'll get that error once your numbers are greater than sys.maxsize
:
一旦您的数字大于 ,您就会收到该错误sys.maxsize
:
>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
You can confirm this by checking:
您可以通过检查来确认这一点:
>>> import sys
>>> sys.maxsize
2147483647
To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:
要获取更高精度的数字,请不要传递在幕后使用有界 C 整数的 int 类型。使用默认浮点数:
>>> preds = np.zeros((1, 3))
回答by sammy ongaya
You can use dtype=np.int64 instead of dtype=int
您可以使用 dtype=np.int64 而不是 dtype=int
回答by plugwash
Could anyone help explain why
谁能帮忙解释一下原因
In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.
在 Python 2 中,python "int" 相当于 C long。在 Python 3 中,“int”是一种任意精度类型,但 numpy 在创建数组时仍然使用“int”来表示 C 类型“long”。
The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.
C long 的大小取决于平台。在 Windows 上,它始终是 32 位。在类 Unix 系统上,通常在 32 位系统上为 32 位,在 64 位系统上为 64 位。
or give a solution for the code on windows? Thanks so much!
或为 Windows 上的代码提供解决方案?非常感谢!
Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-inthe most sensible choice would probably be np.int64
选择大小与平台无关的数据类型。您可以在https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in找到该列表, 最明智的选择可能是 np.int64