Python program to find standard deviation

Standard deviation in Python: Here, we are going to learn how to find the standard deviation using python program? By Anuj Singh Last updated : January 04, 2024

Problem statement

Given a dataset (list), you have to write a Python program to find the standard deviation based on the given dataset.

Standard deviation in Python

While dealing with a large data, how many samples do we need to look at before we can have justified confidence in our answer? This depends on the variance of the dataset.

Variance tells us about the divergence and the inconsistency of the sample. The standard deviation of a collection of values is the square root of the variance. While it contains the same information as the variance. But Standard deviation is quite more referred. Why? Look at the below statement:

  • The mean income of the population is 846000 with a standard deviation of 4000.
  • The mean income of the population is 846000 with a variance of 16000000.

Now see which statement is more favorable and therefore we use standard deviation.

So in this article, we are going to build a function for finding the standard deviation.

So the following function can be used while working on a program with big data which is very useful and help you a lot.

So here is the function code:

Python program to find standard deviation

# Code to find standard deviation

# Defining the function to find the
# standard deviation
def stdv(X):
    mean = sum(X) / len(X)
    tot = 0.0
    for x in X:
        tot = tot + (x - mean) ** 2
    return (tot / len(X)) ** 0.5

# Main code
# Simple dataset
sample = [1, 2, 3, 4, 5]
print("Standard Deviation of the sample is: ", stdv(sample))

sample = [1, 2, 3, -4, -5]
print("Standard Deviation of the sample is: ", stdv(sample))

sample = [10, -20, 30, -40, 50]
print("Standard Deviation of the sample is: ", stdv(sample))

Output

The output of the above example is:

Standard Deviation of the sample is:  1.4142135623730951 
Standard Deviation of the sample is:  3.2619012860600183 
Standard Deviation of the sample is:  32.61901286060018 

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.