In: Computer Science
(Python)
a) Using the the code below write a function that takes the list xs as input, divides it into nss = ns/nrs chunks (where nrs is an integer input parameter), computes the mean and standard deviation s (square root of the variance) of the numbers in each chunk and saves them in two lists of length nss and return these upon finishing.
Hint: list slicing capabilities can be useful in implementing this function.
from random import random as rnd
ns = 100
nr = 10
xs = [None] * ns
def nsums(ns, nr):
for n in range(ns):
xsum = 0.
for i in range(nr):
xd = rnd() - 0.5
xsum += xd
xs[n] = xsum / nr # mean of the nr random numbers
return (xs)
b) Keeping the number of samples ns fixed, generate the means and standard deviations lists using the function in part a for several nrs values - for example, for nrs = 10, 20, 200. Then rescale the means by dividing each mean in the list by its error, si / √nrs, where si is the standard deviation of the i-th chunk.
Python code follows:
#Using the the code below write a function that takes the list xs as input, divides it into nss = ns/nrs chunks
#(where nrs is an integer input parameter), computes the mean and standard deviation s (square root of the variance)
#of the numbers in each chunk and saves them in two lists of length nss and return these upon finishing.
import statistics
import math
from random import random as rnd
ns = 100
nr = 10
xs = [None] * ns
# Returns a list of length ns with each item as the average of nr random numbers
def nsums(ns, nr):
for n in range(ns):
xsum = 0.
for i in range(nr):
xd = rnd() - 0.5
xsum += xd
xs[n] = xsum / nr # mean of the nr random numbers
return (xs)
#PART A solution follows
def chunker (xs, nrs):
ns = len (xs)
splitlst = [xs [i:i+nrs] for i in range(0, ns, nrs)]
meanlst = [statistics.mean (l) for l in splitlst]
stdevlst = [statistics.stdev (l) for l in splitlst]
return meanlst, stdevlst
#Part B, rescaler function
def rescaler (meanlist, stdevlist, nrs):
sqrtnrs = math.sqrt (nrs)
l = [meanlist[i] / stdevlist [i] * sqrtnrs for i in range (len (meanlist))]
return l
# Part B, calling with different nrs values 10, 20, 30
l = nsums (ns, nr)
m, s = chunker (l, 10)
print ("Means 10:", m,"\nStandard deviations 10:", s)
m, s = chunker (l, 20)
print ("Means 20:", m,"\nStandard deviations 20:", s)
m, s = chunker (l, 30)
print ("Means 30:", m,"\nStandard deviations 30:", s)
print ("\n\nRescaled means list:")
print (rescaler (m, s, 30))