使用numpy数组向左移1 [英] Left shifting 1 by large numbers using numpy array

查看:198
本文介绍了使用numpy数组向左移1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python确实可以左移大整数

Python can indeed left shift a bit by large integers

1L << 100
# 1267650600228229401496703205376L

但是NumPy似乎有一个问题:

But NumPy seemingly has a problem:

a = np.array([1,2,100])
output = np.left_shift(1L,a)
print output 
# array([          2,           4, 68719476736])

有没有一种方法可以使用NumPy的left_shift操作来克服?单独访问数组元素会产生相同的错误结果:

Is there a way to overcome this using NumPy's left_shift operation? Individually accessing the array elements gives the same incorrect result:

1L << a[2]
# 68719476736

推荐答案

Python long 值与 a 中保存的整数类型不同.具体来说,Python long 值不限于32位或64位,而是可以占用任意数量的内存.

Python long values aren't the same type as the integers held in a. Specifically, Python long values are not limited to 32 bits or 64 bits but instead can take up an arbitrary amount of memory.

另一方面,NumPy将创建 a 作为 int32 int64 整数值的数组.当您向左移动该数组时,您将返回具有相同数据类型的数组.内存不足,无法容纳 1<<100 ,并且左移的结果会使它在数组中分配的内存溢出,从而产生错误的结果.

On the other hand, NumPy will create a as an array of int32 or int64 integer values. When you left-shift this array, you get back an array of the same datatype. This isn't enough memory to hold 1 << 100 and the result of the left-shift overflows the memory it's been allocated in the array, producing the incorrect result.

要容纳较大的整数,您必须指定 a 以具有 object 数据类型.例如:

To hold integers that large, you'll have to specify a to have the object datatype. For example:

>>> np.left_shift(1, a.astype(object))
array([2, 4, 1267650600228229401496703205376L], dtype=object)

object 数组可以包含不同类型的混合,包括无限制大小的Python long /integer值.但是,当使用 object 数组时,同质数据类型NumPy数组的许多性能优势将丢失.

object arrays can hold a mix of different types, including the unlimited-size Python long/integer values. However, a lot of the performance benefits of homogeneous datatype NumPy arrays will be lost when using object arrays.

这篇关于使用numpy数组向左移1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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