Quantcast
Channel: MATLAB Central Newsreader Recent Posts
Viewing all articles
Browse latest Browse all 19628

How to avoid wrong answers in simple arithmetic expressions.

$
0
0
I tried the following cody problem for fun:
[quot]
Given an amount of currency, return a vector of this form:

 [100 50 20 10 5 2 1 0.5 0.25 0.1 0.05 0.01]

Example:

 Input a = 257.68
 Output b is [2 1 0 0 1 1 0 1 0 1 1 3]

Always use bigger bills/coins if possible.
[/quot]

My solution:
function b = makingChange(a)
   v = [100 50 20 10 5 2 1 0.5 0.25 0.1 0.05 0.01];
   for i = 1 : length(v)
      b(i) = floor(a/v(i));
      a = a - b(i)*v(i);
   end
end

But, due to rounding error, this gives a wrong answer for example for a = 135.01.
The problem does not go away even if I replace the last line by a = rem(a, v(i)).
How does one avoid such issues in general?

Viewing all articles
Browse latest Browse all 19628

Trending Articles