MATLAB Answers

I have an issue with the format of number when i use mean2

1 view (last 30 days)
shiraz karray
shiraz karray on 29 Jan 2016
Commented: Walter Roberson on 29 Jan 2016
Hi i m a new user in matlab. I have a problem when i want to calculate
y=mean2((x-mean2(x))/std2(x))
In fact, i should obtain y=0 , but when i use for example this matrix
x=[10 10 9.2 1;8.33 11.66 29 10;4 10 10 2];
i obtain y=-5.5511e-17! could you help me please

  0 Comments

Sign in to comment.

Accepted Answer

Ingrid
Ingrid on 29 Jan 2016
this is very common to floating point operations and basically y == 0 if you compare it to the eps value. You should never compare directly if a variable is equal to zero for this reason but always use abs(y) < eps

  3 Comments

Guillaume
Guillaume on 29 Jan 2016
Ingrid is correct in that the effects you're seeing in simply due to the way floating points are represented by computers. See this for example for more details.
I disagree with using eps (which is effectively eps(1)) as the equality threshold. You can use it, but it's just an arbitrary small value like any other. eps(y) would not be as arbitrary but it is probably too small a threshold.
The key point to take away though is that when you're dealing with calculation involving floating point numbers, you should never use == to compare the results due to the small errors caused by the way these numbers are stored in memory. You should always compared the difference between the two numbers and check that it is smaller than an arbitrary treshold (which can be eps(1) but may just as well be 1e-15, 1e-20, etc. depending on your algorithm).
In summary, to check that two floating point numbers a and b are equal:
abs(a-b) <= arbitrarily_small_threshold
Walter Roberson
Walter Roberson on 29 Jan 2016
There is a whole branch of mathematics that has to do with analyzing how small the "arbitrarily_small_threshold" should be, and how to know when you can stop adding terms from a theoretically infinite series.
The situation is like noticing,
"1/3 = 0.33333, so 2*(1/3) = 0.66666, so 3*(1/3) must = 0.99999 so why isn't that 1.00000?"

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!