Python 寻找输入数据集的标准差的程序工作不正常

Python 寻找输入数据集的标准差的程序工作不正常

问题描述

我编写了这个程序来计算给定数据集的标准差,但在测试程序时,我没有得到正确的答案,我已经检查了代码,仍然找不到问题所在。 计算标准差的公式为√方差

这是我使用的代码

# THE AIM OF THIS CODE IS TO MAKE A PROGRAM THAT CALCULATES THE STANDARD DEVIATION OF A GIVEN SET OF INTEGERS

numbers = []

while True:

    value = (input("Enter Number: "))
    # Asks for input

    if value.lower() in ("", "q", "quit", "end", "stop", "s"):
        break
        # Instructs the program to break if the value of the input is any of these

    elif value.isdigit():
        numbers.append(int(value))
        # appends the value of the input into the predefined list

    else:
        print("Invalid entry, enter only integers")
        # Tells the user to enter a correct value if he/she enters a non-integer

mean = sum(numbers) / len(numbers)
#Calculates the mean of the given set data

for x in numbers:
    difference = []
    while len(difference) < len(numbers):
        x = x - mean
        #Calculates the difference between the input data and the mean and stores it to another list "difference"
        difference.append(x)

Variance = (sum(difference) ** 2) / len(numbers)
#Calculates the variance for the given set of data

import math

#Variances = 144 ignore this line

StandardDeviation = math.sqrt(Variance)
#Calculates the standard deviation of the input data

print("The Standard Deviation of the given set of data is " + str(StandardDeviation))

解决方案

numbers = []

while True:

    value = (input("Enter Number: "))
    # Asks for input

    if value.lower() in ("", "q", "quit", "end", "stop", "s"):
        break
        # Instructs the program to break if the value of the input is any of these

    elif value.isdigit():
        numbers.append(int(value))
        # appends the value of the input into the predefined list

    else:
        print("Invalid entry, enter only integers")
        # Tells the user to enter a correct value if he/she enters a non-integer

mean = sum(numbers) / len(numbers)
#Calculates the mean of the given set data

n = 0
for x in numbers:
    n += (x - mean) ** 2



StandardDeviation = (n / (len(numbers) - 1)) ** 0.5

print(str(StandardDeviation))

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程