Matlab function "mean" returns the exact same value for "uint16" and "double" values, not for single values
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Teja Muppirala
le 13 Avr 2011
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])
1 commentaire
Mike Hosea
le 13 Avr 2011
One minor note: while MEAN does not currently error when given integer class inputs like 'uint16', I would not advise anyone to rely on this behavior. The current behavior is inherited from SUM, but non-float input is not intentionally supported in MEAN. Type "help mean" and note
Class support for input X:
float: double, single
Plus de réponses (2)
Andreas Goser
le 13 Avr 2011
The issue in the code you use is not in MEAN, but in ==.
mean(double(s)) and mean(single(s)) return similar results, but not identical. And the reason is simply the nature of the data precision. It is not practical to write code that uses == in such case. But maybe you just used this code as an example for this posting. More info in this solution document.
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!