Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to generate random int64 array in numpy?

I want to make random array of int64 uniformly distributed in some range that is not within int32 limits.

There is randint and random_integers but they work with int32; supplying big upper limit produces high is out of bounds for int32.

How do I generate random int64 array with specified range?

Possible solutions:

  • Use floats generator. Won't it have poor resolution in this case?
  • Generate random bytes, interpret them as int64 array and then normalize via lower + x % (upper - lower). But do int32 generation has same normalization? Doesn't it affect uniformity?

Didn't I miss some more concise and convenient ways?

Why do random methods only produce floats and int32?

like image 607
George Sovetov Avatar asked Apr 22 '16 15:04

George Sovetov


1 Answers

Edit:

Using dtype on windows with numpy > 1.11.0:

As @John Y suggestion, it seems possible to cast integers to the desired format using dtype as a named parameter with np.random.randint:

a = np.random.randint(2147483647, 9223372036854775807, size=3, dtype=np.int64)

[end edit]

You can generate an array directly by setting the range for randint; it is likely more efficient than a piecemeal generation and aggregation of an array:

Docstring: (numpy randint)

randint(low, high=None, size=None)

size range if int 32:

ii32 = np.iinfo(np.int32)
iinfo(min=-2147483648, max=2147483647, dtype=int32)

size range for int64 <-> c long

ii64 =  np.iinfo(np.int64)
iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

Generate an array of int64 of val > int32.max:

a = np.random.randint(2147483647, 9223372036854775807, size = 3)
array([4841796342900989982,   43877033468085758,  205656391264979944])

checking the type of the data: gives int64 as expected

a.dtype
dtype('int64')


numpy.randint gives you a uniform distribution across the specified range (attention, the range is exclusive of both ends, unlike python randint)

like image 123
Reblochon Masque Avatar answered Sep 22 '22 08:09

Reblochon Masque