MATLAB: Sum(X) = 1 but Sum(X)==1 produces logical 0

booleanfalselogical 0sum

Can someone please explain this?
sum([Node(temp).pbelief])
ans =
1.0000
K>> sum([Node(temp).pbelief])==1
ans =
0
By the way:
Node(temp(1)).pbelief
ans =
0.0024
K>> Node(temp(2)).pbelief
ans =
0.9976

Best Answer

This does not seem like a limitation/bug in MATLAB. Use the long fixed decimal format before displaying your values:
>> format long
There is a possibility for a discrepancy in the values.
For example, sum([Node(temp).pbelief]) could actually hold 1.0000100, in which case the equality condition is bound to fail.
You could also use "format hex" to view the hexadecimal representation of your sum, and compare it to the hexadecimal representation of 1.
In general, it is not advisable to compare the equality of two values directly, as you have done in this case. It is better to compare their difference to a small predefined tolerance value.
>> abs(sum([Node(temp).pbelief]) – 1) <= 0.0001