Why numpy.var() can be Inaccurate When Computing Matrix Variance? – Numpy Tips

By | September 15, 2019

We can use numpy.var() function to compute matrix variance.

Calculate Average, Variance, Standard Deviation of a Matrix in Numpy

However, numpy.var() function may be inaccurate when computing matrix variance.

In this tutorial, we will use an example to disucss this problem.

Preliminaries

import numpy as np

Create a 2 * (512 *512) matrix with float32

a = np.zeros((2, 512*512), dtype=np.float32)

Change value of this matrix

a[0,:] = 1.001
a[1:0] = 0.001

Calculate the variance with np.var() and float32

v1=np.var(a)

The output is: 0.2505

Calculate the variance with float64

v2 = np.var(a, dtype=np.float64)

The output is: 0.2505002733883863

From the result, we will find v1 ≠ v2, which means we should use np.float64 to comute matrix variance.

Leave a Reply