Why isn't MATLAB counting this as equal to 1?
Show older comments
I've been writing a code, a small part of which checks whether some of the inputs sum to 1 (as they're all proportions of a whole). If they do, the code continues. If not, the code stops and throws up an error message.
a = 0.4;
b = 0.3;
c = 0.2;
d = 0.1;
total = [a,b,c,d];
if sum(total) ~= 1
warning('Sum of a,b,c,d must be 1.')
return
end
The example I've given here DOES NOT WORK, even though a+b+c+d = 1. It throws up the error message and stops the script.
To be clear, this works fine for a,b,c and d = 0.25. It works for a = 0.5, b = 0.4, c and d = 0.05. It doesn't work for the example I've given, and it doesn't work for a,b,c = 0.3, d = 0.1. I haven't checked other combinations exhaustively.
Any help would be greatly appreciated, thanks.
2 Comments
Adam
on 8 Nov 2018
(most) Floating point numbers cannot be represented with 100% accuracy so even though they may appear to be exact they are not and when you do maths with these those minor errors accumulate. You should never test equality of floating point numbers though unless there is some very clear purpose in doing so (e.g. two places that implement the same maths to get to a result)
BecomeAnAstronaut
on 8 Nov 2018
Accepted Answer
More Answers (1)
madhan ravi
on 8 Nov 2018
Edited: madhan ravi
on 8 Nov 2018
if abs(sum(total-1)) < 1e-4 %edited
The above is equivalent to
if sum(total)==1
12 Comments
madhan ravi
on 8 Nov 2018
Edited: madhan ravi
on 8 Nov 2018
add tolerance see https://www.mathworks.com/help/matlab/ref/eq.html#bt2klek-3 for further explanation
BecomeAnAstronaut
on 8 Nov 2018
madhan ravi
on 8 Nov 2018
Anytime :)
BecomeAnAstronaut
on 8 Nov 2018
Edited: BecomeAnAstronaut
on 8 Nov 2018
madhan ravi
on 8 Nov 2018
what are you trying to do and what doesn't work ? did you see Adams comment?
BecomeAnAstronaut
on 8 Nov 2018
madhan ravi
on 8 Nov 2018
Edited: madhan ravi
on 8 Nov 2018
I just want to stop the code if the four numbers a,b,c,d don't sum to 1.
if (sum(total)~=1)<1e-4
break %use break to stop
end
BecomeAnAstronaut
on 8 Nov 2018
It should be
if abs( sum(total)-1 ) < 1e-4
madhan ravi
on 8 Nov 2018
Thank you @Matt edited already
BecomeAnAstronaut
on 8 Nov 2018
madhan ravi
on 8 Nov 2018
Edited: madhan ravi
on 8 Nov 2018
There was a mistake in my part (corrected it)
see https://www.mathworks.com/matlabcentral/answers/428577-very-odd-error-with-simple-multiplication-ok-not-so-odd#answer_345716 for further explanation on float numbers
make sure to accept the answer if it answered your question so people know the question is solved
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!