In: Computer Science
Write the python code that generates a normal sample with given μ and σ, and the code that calculates m (sample mean) and s (sample standard deviation) from the sample.
Code for generate a normal sample:
import numpy as np
def main():
#get input for mean
mean = int(input("Please enter mean: "))
#get input for standard deviation
stdev = int(input("Please enter standard
deviation: "))
#generate samples with mean and standard
deviation
samples = generateSamples(mean, stdev,
100000)
print('Normal sample: ', samples)
print('Mean:', samples.mean())
print('Standard deviation:',
samples.std())
return
def generateSamples(mean, stdev, n=1):
# Calculate mu and sigma of normal
distribution
meanSqr = mean ** 2
phi = (stdev ** 2 + meanSqr) ** 0.5
sigma = (np.log(phi ** 2 / meanSqr)) **
0.5
mu = np.log(meanSqr / phi)
# Generate normal population
normal_samples = np.random.lognormal(mu, sigma ,
n)
# Convert single sample (if n=1) to a float,
otherwise leave as array
normal_samples = normal_samples[0] if
len(normal_samples) == 1 else normal_samples
return normal_samples
#Call method
main()
Code Screenshot:
Sample output: