Jiahui Guo
Jiahui Guo

Reputation: 135

Matlab gives wrong answer on mod(), isequal(), floor() function with a vector parameter

I am using matlab to solve a mixed integer programming, after I obtain a solution from linprog, I want to evaluate whether they are all integers(x is n dimensions), but I cannot figure out a way to do this.

All the functions, such as mod(x,1) == 0, isequal(x,floor(x)) will give a wrong anwser.

More strange is, if you manually input a vector with the same parameter, it will turn out to be right.

The result is shown: (all the x here is obtained from the result of linprog). Anyone can help with this or bring out some other useful way to evaluate this?

K>> x

x =

    7.0000
    1.0000

K>> mod(x,1)

ans =

    0.0000
    1.0000

K>> x

x =

    6.0000
    3.0000

K>> isequal(x,floor(x))

ans =
    0

Upvotes: 0

Views: 1866

Answers (1)

Lumen
Lumen

Reputation: 3574

What seems to be an integral 1 coming from linprog, actually is a floating point number very close to 1, but not equal to it. It's just that you (by default) cannot tell the difference by outputting the number in MATLAB. See this Question about comparing floating point values. Also, see the MATLAB manual page about display format of numbers.

By default, MATLAB displays numbers using format short:

format sets the display of floating-point numeric values to the default display format, which is the short fixed decimal format. This format displays 5-digit scaled, fixed-point values.

So, 1 – 1e–10 would be displayed as 1 even though it is not equal to 1. Likewise, mod(1 – 1e–10, 1) would be displayed as 1, even though it really is 1 – 1e–10.

If you manually set x to its displayed representation, all the less significant digits are truncated, “strangely” giving you the expected results.

Check x after typing the command format long.

Upvotes: 2

Related Questions