Created
February 21, 2021 07:34
-
-
Save isopropylcyanide/a9163f50be9901666d09e9066166002d to your computer and use it in GitHub Desktop.
Generate N random numbers in range(A, B) with an average mean of X
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from math import ceil, floor | |
""" | |
The idea is to assume a normal Gaussian distribution around the given | |
average for a given range. Random numbers will be generated on either | |
side of the normal. | |
""" | |
def randomCeilOrFloor(X): | |
""" | |
Randomly choose ceil or float for a given number on a coin toss | |
""" | |
toss = np.random.randint(2) | |
return ceil(X) if toss == 1 else floor(X) | |
def generate(N, A, B, average): | |
""" | |
Given a range A, B and a standard deviation, we can construct a | |
normal distribution of random variables of size(N) | |
Here, N should be less than 10^8 | |
numpy.random.normal(loc = 0.0, scale = 1.0, size = None) : | |
creates an array of specified shape and fills it with random | |
values which is actually a part of Normal(Gaussian)Distribution. | |
""" | |
mean = A + (B - A) / 2 | |
if average > B or average < A: | |
return [] | |
std_deviation = abs(mean - average) | |
return np.random.normal(average, std_deviation, size=(N)) | |
if __name__ == "__main__": | |
rand_range = generate(N=40, A=0.66, B=5, average=2.4) | |
# rand_range = generate(N=100, A=100, B=200, average=181) | |
sum_random = sum(rand_range) | |
print("Average numbers: {0}".format(sum_random / 40)) | |
for i in rand_range: | |
print(randomCeilOrFloor(i)), | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment