MATLAB: Matlab function “mean” returns the exact same value for “uint16” and “double” values, not for single values

different resultsdoubleMATLABmeanprecisionsingleuint16

Hello,
I'm using Matlab 2010b. I noticed that mean(s) and mean(double(s)) return the same value whereas mean(s) and mean(single(s)) does not. Why?
s = uint16(2^16*rand(1000,1));
mean(s)==mean(double(s))
mean(s)==mean(single(s))
Thank you for your help. Stéphane

Best Answer

Expanding on Andreas's answer a little bit,
For single precision, the consecutive integers are available only until 2^24 (16777216). The next number is 16777218. So your expressions are not equal for the same reason that A and B here are not equal:
s = [16777210 5 6]
s_single = single(s)
A = cumsum(s)
B = cumsum(s_single)
Try these:
single(16777210) + [0:10]
cumsum(single([16777214 1 1 1 1 1 1 1]))
So there is inevitable roundoff error after that threshold.
What MEAN does, is first add up all the numbers and then divides the result by the number of elements. The sum of s is much larger than 2^24, so when adding up those numbers in single precision, you will get round-off error.
So why does it sum correctly without any roundoff error for UINT16s then? The reason is that SUM will add UINT16s using double precision arithmetic. Try it:
s = uint16(47)
class(s)
sum(s)
class(sum(s))
There are ways to show this effect for double precision numbers as well:
L = 1e308 %A is a large double precision number
mean([L L]) % Should be = L, but it is Inf
But curiously enough, there are some exceptions...
mean([L L -L -L])
cumsum([L L -L -L])