Question

I'm a MATLAB beginner. Here's the problem:

>> a = floor(7/2.5)

a =

      2.00

>> b = rem(7,2.5)

b =

      2.00

>> c = floor(b/2)

c =

         0

c should be 1, right? Why is it 0???

It is different when b = 2 is entered directly as follows:

>> b = 2

b =

      2.00

>> c = floor(b/2)

c =

      1.00
Was it helpful?

Solution

In two words: truncation errors.

You're right, c should be 1.0 in exact arithmetic. However, since you used a float in the arguments of rem, you get the answer as a float. Apparently, b is not exactly 2, but 2.0, which means that it is a double very close to 2. Therefore, b/2 becomes the double 1.0, apparently in this case its value is slightly less than one, giving you a 0 as the integer value. If you want to prevent this, use both floor and ceil, and compare the values.

If you want to convert the answer to integer, just use round instead of floor.

OTHER TIPS

If you add the line

d = b-a

to your example you'll see the result

    d =

 -4.4409e-016

meaning Matlab calculated a number close to, but not exactly, 2 for b. This comes up quite a bit in working with floating point numbers. Try

help eps

for more information.

Numerical issues of this sort are also dealt with in the MATLAB FAQ

Yeah that is a numerical issue. You should use such things with care. If you want exact arithmetic , you should try 'sym' for your number e.g.

b=rem(sym(7),sym(2.5))

Then you will not any such errors, but your computations will be much slower.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top