Unrecognised error

Asked

Viewed 46 times

0

I have to do a function where I present the result of the mean and standard deviation:

def challenge2(*args):
    """return average and standard deviation"""
    t=0
    for i in lista:
        t=i**2
        avg=sum(lista)/len(lista)
        std=(t/len(lista)-avg**2)**(1/2)
    print("The avarege is:",avg)
    print("The standard deviation is:",std)

lista = [1,2,3,4,5,6]

challenge2(lista)

However, output is wrong for standard deviation:

The avarege is: 3.5
The standard deviation is: (1.5308084989341916e-16+2.5j)

Can anyone identify where the mistake is?

2 answers

0

Taking into account that to calculate the standard deviation it is necessary to make a sum, you must, in the loop for scrolling through the list, add to the variable t the value that should be added to the sum and, after the loop, divide that value by the list size minus 1 (or only by the list size if it is a population - in this case I considered that the list represents a sample. If it is a population, remove the " -1" from the division). The complete code looks like this (I used the function sqrt library Math for the calculation of the square root):

import math

def challenge2(*args):
    """return average and standard deviation"""
    t=0
    avg = sum(lista)/len(lista)
    
    for i in lista:
        t = t + (i - avg) ** 2
        
    std = math.sqrt((t / (len(lista) - 1)))
        
    print("The avarege is:", avg)
    print("The standard deviation is:", std)

lista = [1,2,3,4,5,6]

challenge2(lista)

Something important: in your code, the calculation of the average was being carried out within the loop that runs through the list, which is unnecessary, because it is possible to calculate it only once before the for.

See working on repl.it

  • Thank you so much! It helped a lot

0

From what I understand you want to implement a function that returns both to Arithmetic Mean as to the Standard Deviation values. To solve this question you can use the following algorithm:

from math import pow, sqrt


def media_desvio_padrao(lis):
    soma = sum(lis)
    quant = len(lis)
    avg = (soma / quant)

    soma_t = 0
    for item in lis:
        soma_t += pow((item - avg), 2)
    std = sqrt(soma_t / quant)
    return avg, std


valores = [1, 2, 3, 4, 5, 6]

media, desvio_padrao = media_desvio_padrao(valores)

print(f'\033[32mA Média Aritmética é: {media:.2f}')
print(f'O Desvio Padrão é: {desvio_padrao:.2f}')

Note that in this algorithm has been implemented a function that takes as parameter a list and returns two values that are: mean and standard deviation.

When we execute this code, we receive the following outputs

A Média Aritmética é: 3.50
O Desvio Padrão é: 1.71

Details

When we execute the code the list is passed as argument to the function media_desvio_padrao. This function calculates the sum of the values of the list (sum), the number of values of the list (Quant) and the arithmetic mean of these values (avg).

Then the list of valores and traversed by the loop of repetition for and, with each interaction of the photon, the variable soma_t, which is responsible for the accumulation of the operation pow((item - avg), 2). The desvio padrão.

Subsequently the function media_desvio_padrao returns two values, who are: avg (arithmetic mean) and std (standard deviation).

Then the results are displayed formatted to two decimal places.

Now, imagine that you want to work with an indefinite amount of lists and values. In this case, you will need an algorithm that is able to work with multiple lists. For this situation we can use the following algorithm:

from math import pow, sqrt


def media_desvio_padrao(lis):
    soma = sum(lis)
    quant = len(lis)
    avg = (soma / quant)

    soma_t = 0
    for item in lis:
        soma_t += pow((item - avg), 2)
    std = sqrt(soma_t / quant)
    return avg, std


valores = list(map(int, input('Digite os valores: ').split()))

media, desvio_padrao = media_desvio_padrao(valores)

print(f'\033[32mA Média Aritmética é: {media:.2f}')
print(f'O Desvio Padrão é: {desvio_padrao:.2f}')

When we executed this second algorithm we received the following message: Digite os valores: . Right now we must type all the values of the list in the same line, separated for a single space and press Enter.

From now on all operations described above will be carried out.

Observation 1

With this code we can calculate the Média Aritmética and the Desvio Padrão of any lists containing values inteiros.

Observation 2

With this code, we can enter per list, how many values we want.

Observation 3

To end inserting values into the list, simply press the button enter.

  • Show! I managed to do it here, thank you!

  • If the answer worked correctly it would be good tone mark it by clicking on V next to the answer. Because, marking this way, the answer is in evidence for new users.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.