0

I intend to create 100 binary arrays of shape (8, 8, 8) in a way that for each of its arrays about 40% of the elements are zero and the rest are 1. I have the following code:

num1=100
size = (num1, 8, 8, 8)
prob_0 = 0.4 # 40% of zeros
prob_1 = 1 - prob_0 # 60% of ones
P = np.random.choice([0, 1], size=size, p=[prob_0, prob_1])

However, it is probabilistic and I am looking for its deterministic version.

Further elaboration: In the above code, it is theoretically possible that I get an array with all the elements being 1 for instance. What I'm looking for is a method that controls value assignment in a way I only get to have arrays that only 40% of its elements are 0 and the rest are 1. In other words, each of the (8, 8, 8) arrays should have a constant number of ones and zeros.

3
  • Just to make it clear, the constraint is to have the same number of 0's and 1's between runs, but their positions are not necessarily deterministic Commented Aug 23, 2021 at 15:29
  • Between runs? @ronpi Commented Aug 23, 2021 at 18:28
  • Output of first run, compared to the output from the second run of the same program Commented Aug 23, 2021 at 20:32

1 Answer 1

1

Just use numpy's Generator to get deterministic results. This is how you can get the exact same array each run.

from numpy.random import default_rng

rng = default_rng(42)    # default random generator

num1=100
size = (num1, 8, 8, 8)
prob_0 = 0.4 # 40% of zeros
prob_1 = 1 - prob_0 # 60% of ones
P = rng.choice([0, 1], size=size, p=[prob_0, prob_1])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. But in fact, it is not what I'm after. I have added extra info to my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.