Write a program to compute the mean x¯x¯ and standard deviation σσ of a finite sequence xixi. Your program should accept a vector xx of dimension nn as input and produce the standard deviation of the sequence as output. For the standard deviation, try both the two-pass formula

Respuesta :

Answer:

To output the standard deviation using the two-pass formula:

 standard deviation = [(1/n-1)∑(x - mean)^2]^0.5

def std_twopass( vector ):

     total_sum = 0

     mean = sum(vector)/len(vector)

     for v in vector:

           total_sum += (v - mean)**2

     sample = 1 / ( len( vector) - 1)

     std = (sample * total_sum )**0.5

     print( "standard deviation using two-pass formula: ", std)

- Using one-pass formula

standard deviation = [(1/n-1)∑(x^2 - n* mean^2)]^0.5

def std_onepass( vector ):

     total_sum = 0

     mean = sum(vector)/len(vector)

     for v in vector:

           total_sum += (v**2) - ( len( vector ) *( mean**2))

     sample = 1 / ( len( vector) - 1)

     std = (sample * total_sum )**0.5

     print( "standard deviation using one-pass formula: ", std)

Explanation:

Both python functions calculates the standard deviation of a sample population, using the two-pass and one-pass formula respectively.