I have a code which calculates the square of a number using Gaussian distribution in python. Now my task is to calculate the variance for the same. But when I try, i keep getting error. The code is as follows:
import random
def generate_data(size):
n = 5
m =0.5
mu, sigma = n ** 2, m/3
return [random.gauss(mu, sigma) for _ in range(size)]
def average(ls):
avg = sum(ls) / len(ls)
variance = (sum(ls) - sum(avg)) ** 2 / len(ls)
return variance
I am not good in statistics, so I might be wrong with the formula too. and I am also a beginner in python.The error I get is
'float' object is not iterable
Your variance formula should be
variance = sum(map(lambda x: (x-avg) ** 2, ls)) / len(ls)
Since variance = sigma^2
you can test your code by printing math.sqrt(variance)
import random, math
def generate_data(size):
n = 5
m = 0.5
mu, sigma = n ** 2, m/3
return [random.gauss(mu, sigma) for _ in range(size)]
def variance(ls):
avg = sum(ls) / len(ls)
variance = sum(map(lambda x: (x-avg) ** 2, ls)) / len(ls)
return variance
print(0.5/3) #0.16666666666666666
print(math.sqrt(variance(generate_data(100)))) #0.15702629417476763
print(math.sqrt(variance(generate_data(1000)))) #0.16248850600497303
print(math.sqrt(variance(generate_data(10000)))) #0.16774494705918871
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments