user12348400
user12348400

Reputation:

Using probability in python

Let's say i have a 2D array named grid of size (N,N).The NxN array cells can either be 0 or 1.First i initialise all the array cells as 0.Then what i would like to do is iterate through the array and change 0's to 1's with given probability p.What i mean is this:

p=0.5
for i in range(0,N-1)
  for j in range(0,N-1) //iteration through every cell
    // grid[i][j] has p=50% chance to change from 0 to 1

How could this be implemented?

Upvotes: 1

Views: 88

Answers (2)

fuglede
fuglede

Reputation: 18201

If performance matters, and you don't mind a dependency on SciPy, there's

import scipy.stats as st
grid = st.bernoulli.rvs(0.5, size=(N, N))

or NumPy's

import numpy as np
grid = np.random.binomial(1, 0.5, size=(N, N))

Upvotes: 1

StupidWolf
StupidWolf

Reputation: 46908

I am trying a solution here. Sample from 0-1 , according to the dimensions you want. Then according to p, converting those > p to 1 and < p to 0 will be what you need

import numpy as np
p=0.3
N=5
(np.random.random_sample((N, N)) > p).astype(int)

Upvotes: 0

Related Questions