Why the statement (0.15-0.1)==0.05 is false in matlab?
4 views (last 30 days)
Show older comments
Hi, i am writing a function that takes in a sum of money as its only input argument and returns 10 values representing the minimum number of Australian notes/coin necessary to make the specified amount. In Australia, we use the following monetary denomination: 100, 50, 20, 10, 2, 1, .50, .20, .10, .05
I found that my code does not work when the result includes .10 and .05. (for example change(20.15))
debugging my code i found out that the logic result in matlab for an operation like (0.15-0.1)==0.05 is 0, how is that possible? i tried in octave and i got the same results. is there a way to fix it?
please find my code down below.
function [r] = change(v)
r=zeros(10,1);
M=[100,50,20,10,2,1,0.5,0.2,0.1,.05]; %
i=1;
while v>= M(10) %minimun denomination bill
if v>=M(i)
v=v-M(i);
r(i)=r(i)+1;
else
i=i+1;
end
end
disp('bills needed');
for i = 1 : 10
if r(i)~= 0
disp([num2str(r(i)),' x ',num2str(M(i)),'AUD']);
end
end
Thanks in advance.
2 Comments
Stephen23
on 15 Mar 2018
Edited: Stephen23
on 15 Mar 2018
Small differences in the floating-point values mean that those rows are actually different. Floating-point numbers have been explained many times on this forum:
etc, etc, etc
Always use a tolerance when comparing floating point values.
A simple alternative would be to measure the values in cents, which would mean that you could use integer values for all of your calculations (and you would not need floating point numbers at all).
James Tursa
on 15 Mar 2018
>> num2strexact(0.15)
ans =
0.1499999999999999944488848768742172978818416595458984375
>> num2strexact(0.1)
ans =
0.1000000000000000055511151231257827021181583404541015625
>> num2strexact(0.15-0.1)
ans =
4.9999999999999988897769753748434595763683319091796875e-2
>> num2strexact(0.05)
ans =
5.000000000000000277555756156289135105907917022705078125e-2
Answers (0)
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!