performance - python : Is there a way to keep an automatic conversion from int to long int from happening?

标签 performance integer python-2.x long-integer

考虑这个例子:

>>> from sys import maxint
>>> type(maxint)
<type 'int'>
>>> print maxint
9223372036854775807
>>> type(maxint+2)
<type 'long'>
>>> print maxint+2
9223372036854775809
>>> type((maxint+2)+maxint)
<type 'long'>
>>> print ((maxint+2)+maxint)
18446744073709551616

Python 将 autopromote从一个 int,在本例中是一个 64 位整数值(OS X,python 2.6.1)到一个任意精度的 python long 整数。尽管类型不同,但它们很相似,Python 允许使用常用的数字运算符。通常这很有用,例如能够在 32 位机器上使用需要 64 位值的代码。

但是,任意精度操作比原生 int 操作慢得多。例如:

>>> print maxint**maxint # execution so long it is essentially a crash

有没有办法阻止或禁止将 Python int 自动提升为 Python long

最佳答案

所以你想抛弃唯一正确的方式并在溢出时复古。你傻。

C/C++/C#/Java 风格的溢出没有好的好处。 It does not reliably raise an error condition .对于 C 和 C99,它是 ANSI 和 POSIX 中的“未定义行为”(C++ 要求取模返回)并且它是一个已知的安全风险。你为什么要这个?

Python method无缝溢出到长是更好的方法。我相信这与 Perl 6 所采用的行为相同。

您可以使用 Decimal module获得更多有限溢出:

>>> from decimal import *
>>> from sys import maxint
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1,
flags=[], traps=[DivisionByZero, Overflow, InvalidOperation])

>>> d=Decimal(maxint)
>>> d
Decimal('9223372036854775807')
>>> e=Decimal(maxint)
>>> f=d**e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/decimal.py", line 2225, in __pow__
    ans = ans._fix(context)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/decimal.py", line 1589, in _fix
    return context._raise_error(Overflow, 'above Emax', self._sign)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/decimal.py", line 3680, in _raise_error
    raise error(explanation)
decimal.Overflow: above Emax

您可以使用 Decimal 类设置精度和边界条件,几乎可以立即溢出。您可以设置陷阱。您可以设置最大值和最小值。真的 - 它如何变得比这更好? (老实说,我不知道相对速度,但我怀疑它比 numby 快,但显然比 native 整数慢......)

对于您的特定图像处理问题,这听起来像是考虑某种形式的 saturation arithmetic 的自然应用程序.您还可以考虑,如果您在 32 算术上有溢出,请在明显的情况下沿途检查操作数:pow、**、*。你可以考虑 overloaded operators并检查您不想要的条件。

如果小数、饱和或重载运算符不起作用 -- you can write an extension .如果你想扔掉 Python 的 overflow 方式去复古...

关于performance - python : Is there a way to keep an automatic conversion from int to long int from happening?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4362338/

相关文章:

java - java在使用整数/ double / float 的情况下是否使用内存

php - 当使用 php 和 mysql 在用户输入中使用默认值和 null str 时,我如何使用统一的 sql 进行插入

iphone - 启用 Alpha 混合是否会影响 iPhone 上的性能(填充率)?

node.js - 5 秒未加载,heroku node.js 应用加载缓慢

string - 将数字作为字符串插入到文本列中,SQLite 仍然删除前导零

python - 为什么这种循环导入在 Python 2 中会失败,但在 Python 3 中却不会?

python - 如何防止将字符串分解为字符列表?

python - 安排代码稍后执行

mysql - 增加对mysql的同时请求数

java - 如何实现 JOptionpane 列表选项?