random - Variance using Gaussian distribution Python -


i have code calculates square of number using gaussian distribution in python. task calculate variance same. when try, keep getting error. code follows:

import random def generate_data(size):     n = 5     m =0.5     mu, sigma = n ** 2, m/3     return [random.gauss(mu, sigma) _ in range(size)]   def average(ls):     avg =  sum(ls) / len(ls)     variance = (sum(ls) - sum(avg)) ** 2 / len(ls)      return variance 

i not in statistics, might wrong formula too. , beginner in python.the error is

'float' object not iterable  

your variance formula should be

variance = sum(map(lambda x: (x-avg) ** 2, ls)) / len(ls) 

source

since variance = sigma^2 can test code 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) _ 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 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -