I am generating a 2D array of random integers using numpy:
import numpy
arr = numpy.random.randint(16, size = (4, 4))
This is just an example. The array I am generating is actually enormous and of variable size. Since the numbers are always going to be from 0 to 16, I would like to save some space and have the array be of type uint8
. I have tried the following
arr = numpy.random.randint(16, size = (width, height), dtype = numpy.uint8)
in an attempt to match the behavior of zeros
and ones
, but I get the following error:
Traceback (most recent call last):
File "<ipython-input-103-966a510df1e7>", line 1, in <module>
maze = numpy.random.randint(16, size = (width, height), dtype = numpy.uint8)
File "mtrand.pyx", line 875, in mtrand.RandomState.randint (numpy/random/mtrand/mtrand.c:9436)
TypeError: randint() got an unexpected keyword argument 'dtype'
The docs for randint()
do not mention anything about being able to set the type. How do I create a random array with a specific integer type? I am not tied to any one function, just a uniform distribution from 0 to 16 of type uint8
.
To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand. Parameters : low : [int] Lowest (signed) integer to be drawn from the distribution.
In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.
random. randint. Return random integers from low (inclusive) to high (exclusive).
Numpy's random number routines produce pseudo random numbers using combinations of a BitGenerator to create sequences and a Generator to use those sequences to sample from different statistical distributions: BitGenerators: Objects that generate random numbers.
The quickest way is to use the astype()
method:
x = np.random.randint(16, size=(4,4)).astype('uint8')
This works on any numpy array. But please note that by default it does not check that the casting is valid.
The issue is that np.random.randint cannot specify dtype
import numpy as np
random_array = np.random.randint(0,16,(4,4))
[[13 13 9 12]
[ 4 7 2 11]
[13 3 5 1]
[ 9 10 8 15]]
print(random_array.dtype)
>>int32
random_array = np.array(random_array,dtype=np.uint8)
print(random_array.dtype)
>>uint8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With