2

I want to compare two double values. I know the value of MinimumValue, which is 3.5261e+04. This MinimumValue I got from an array e. My code has to print first statement 'recognized face' because both value are same. But my code is displaying second statement 'unrecognized face'.

What is the mistake in my code?

MinimumValue = min(e)

theta = 3.5261e+04;

if (MinimumValue <= theta)
    fprintf('recognized face\n');
else
    fprintf('unrecognized face\n');
end
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
user3456881
  • 41
  • 2
  • 4
  • 1
    Possible duplicate of http://stackoverflow.com/questions/13699596/is-this-a-matlab-bug-do-you-have-the-same-issue/13699708#13699708 – patrik Mar 27 '14 at 08:15
  • @patrik: it's not a duplicate, because the OP's not checking for *equality*. It's (probably) a display issue. – Rody Oldenhuis Mar 27 '14 at 12:38

1 Answers1

2

There are two approaches:

  1. Replace if MinimumValue<=theta with if MinimumValue == theta. This is the easier but probably poorer approach for your problem.

  2. Chances are, MinimumValue is different from theta by a very small amount. If you are doing some calculations by hand to determine that theta = 3.5261e+04, and believe there are more decimal places, you should use format long to determine the actual value of theta to 15 significant figures. After that, you can use if abs(MinimumValue - theta) <= eps (edit: As patrick has noted in the comment below, you should compare to some user-defined tolerance or eps instead of realmin('double').

elleciel
  • 2,297
  • 3
  • 17
  • 19
  • I have to check for both condition "less than or equal to". – user3456881 Mar 27 '14 at 07:12
  • @user3456881: indeed, print the value of `MinimumValue` with `format long e` turned on; you'll probably see then why the test fails. – Rody Oldenhuis Mar 27 '14 at 07:20
  • 1
    A warning here, I would not recommend comparing to realmin. which is of magnitude `10^-311`. No floating points operations can be of that accuracy. The minimum floating point precision is somewhere of 10^-16. Then the machine error will be significant. This is why a machine epsilon (`eps`) in matlab, which is the maximal precision of floating point operations. This is set to 2^-52. So rather try `if abs(MinimumValue - theta) <= eps`, or better set a tolerance `tol` define by you – patrik Mar 27 '14 at 07:53
  • @patrik: Good catch there, I've edited my response to credit your comment. – elleciel Mar 28 '14 at 06:48