Q:

Numerical accuracy loss in Python

I wish to calculate the standard error of a series of numbers. Suppose the numbers are x[i] where i = 1 ... N. To do this
I set 
averageX = 0.0
averageXSquared = 0.0

I then loop over all i=1,...N and for each I calculate
averageX += x[i]
averageXSquared += x[i]**2

I then divide by N
averageX = averageXC / N
averageXSquared = averageXSquared/N

I then take the square root of the difference
stdX = math.sqrt(averageXSquared - averageX * averageX)

The argument here is sure to always be >=0. 
However if I set all x[i] = 0.07 (for example) then I get a math domain error as the argument of the root function is negative. There seems to be some loss of precision. 
The argument is of the order of 10e-15.
This does not look encouraging. I now have to check myself to see if the result is negative before taking the root.
Or have I done something wrong.

A:

This is not a python problem, but a problem with finite precision in general. If you set all numbers to the same value, the standard error is mathematically 0, but not for a computer. The correct way to handle this, is to set very small values <0 to 0.
x = [0.7, 0.7, 0.7]
average = sum(x) / len(x)
sqav = sum(y**2 for y in x) / len(x)
stderr = math.sqrt(max(sqav - average**2, 0))

