jeudi 10 juin 2021

Python: How do I generate a random matrix of 1.0 and 0.0, but with floats?

I am currently coding Conway's game of life and to add randomization to my world I have implemented a function to create a random matrix with 1 and 0 with n rows and n columns.

The problem is that, for my code to work, I need a random matrix of 1 and 0 but they have to be floats, so 0.0 and 1.0 So I cannot use:

rand_matrix = numpy.random.randint(0, 2, size=n)

Instead I have tried:

n = 10 
one_zero = [0.0,1.0]
rand_matrix = np.array([n*[random.choice(one_zero),random.choice(one_zero)],n*[random.choice(one_zero),random.choice(one_zero)]])

Getting:

[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]] 

But this returns a matrix of different dimensions, what I want is a random n by n matrix. And each row should be a combination of 0.0 and 1.0 randomly chosen.




Aucun commentaire:

Enregistrer un commentaire