Python program to find the variance

Variance in python: Here, we are going to learn how to find the variance of given data set 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 variance based on the given dataset.

Calculating Variance

Variance tells us about the divergence and the inconsistency of the sample. So in this python article, we are going to build a function.

Mathematically we define it as:

variance in Python

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

Python code to find the variance

# Code to find variance in Python

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

# Main code
# simple dataset
sample = [1, 2, 3, 4, 5]
print("variance of the sample is: ", variance(sample))

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

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

Output

The output of the above example is:

ariance of the sample is:  2.0
variance of the sample is:  10.64
variance of the sample is:  1064.0

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.