Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random normal distribution without numpy? (Google interview)

So I have a data science interview at Google, and I'm trying to prepare. One of the questions I see a lot (on Glassdoor) from people who have interviewed there before has been: "Write code to generate random normal distribution." While this is easy to do using numpy, I know sometimes Google asks the candidate to code without using any packages or libraries, so basically from scratch.

Any ideas?

like image 880
Kelsey Avatar asked Jul 20 '26 08:07

Kelsey


1 Answers

According to the Central Limit Theorem a normalised summation of independent random variables will approach a normal distribution. The simplest demonstration of this is adding two dice together.

So maybe something like:

import random
import matplotlib.pyplot as plt

def pseudo_norm():
    """Generate a value between 1-100 in a normal distribution"""
    count = 10
    values =  sum([random.randint(1, 100) for x in range(count)])
    return round(values/count)
    
dist = [pseudo_norm() for x in range(10_000)]
n_bins = 100
fig, ax = plt.subplots()
ax.set_title('Pseudo-normal')
hist = ax.hist(dist, bins=n_bins)
plt.show()

Which generates something like: Pseudo-normal generated sample

like image 57
import random Avatar answered Jul 22 '26 22:07

import random



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!