Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python statistics.variance() Function



The Pythonstatistics.variance() function returns the sample variance of the data i.e., an iterable of at least two-real valued numbers. Variance is the measure of the variability. A large variance indicates that the data is spread out whereas, a small variance indicates that the data is clustered closely around the mean.

Variance is the squared deviation of a variable from the given mean of the dataset. This function measures the spread of random data in a set from its mean or median value.

A low value for variance indicates that the data is common. This function is the square of Standard Deviation of the given data-set.

StatisticsError is raised for the data-set that has less than two values passed as a parameter.

Syntax

Following is the basic syntax for thestatistics.variance() function.

statistics.variance([data], xbar)

Parameters

This function contains iterable real valued numbers, and xbar is the optional parameter that determines the data-set values.

Return Value

Returns the actual variance of the values passed as a parameter.

Example 1

In the below example, we are calculating the variance of the standard deviation usingstatistics.variance() function.

import statisticsx = [2.34, 1.23, 0.23, 7.98, 5.67]y = statistics.variance(x)print("Variance of sample set is % s" % x)

Output

We will get the following output as follows −

Variance of sample set is [2.34, 1.23, 0.23, 7.98, 5.67]

Example 2

Now, we are demonstrating the variance in the range of data types usingstatistics.variance() function.

from statistics import variancefrom fractions import Fraction as fr x = (1, 2, 3, 4, 5, 6)y = (-2, -4, -6, -8, -10)z = (fr(1, 2), fr(3, 4), fr(5, 6), fr(7, 8))print("Variance of x is % s" % variance(x))print("Variance of y is % s" % variance(y))print("Variance of z is % s" % variance(z))

Output

This produces the following result −

Variance of x is 3.5Variance of y is 10Variance of z is 65/2304

Example 3

Here, we are utilizing the xbar parameter usingstatistics.variance function.

import statisticsx = (1, 0.2, 1.23, 4, 5.45)y = statistics.mean(x)print("Variance of sample set is % s" %(statistics.variance(x, xbar = y)))

Output

The result is produced as follows −

Variance of sample set is 5.00713

Example 4

Now we are demonstrating StatisticsError usingstatistics.variance() function.

import statisticsx = []print(statistics.variance(x))

Output

This produces the following result −

Traceback (most recent call last):  File "/home/cg/root/37557/main.py", line 3, in <module>    print(statistics.variance(x))  File "/usr/lib/python3.10/statistics.py", line 767, in variance    raise StatisticsError('variance requires at least two data points')statistics.StatisticsError: variance requires at least two data points
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp