Shop OBEX P1 Docs P2 Docs Learn Events
Floating Point comparisons — Parallax Forums

Floating Point comparisons

RogerInHawaiiRogerInHawaii Posts: 87
edited 2009-10-25 15:19 in Propeller 1
Can you do "greater than" and "less than" comparisons with floating point numbers?

Is this valid?...

fpSomeNumber := 39.0
fpMinNumber := 12.0
fpMaxNumber := 100.0

NumIsGood := true

if ((fpSomeNumber < fpMinNumber) OR (fpSomeNumber > fpMaxNumber))
   NumIsGood := false


Comments

  • BradCBradC Posts: 2,601
    edited 2009-10-25 02:24
    RogerInHawaii said...
    Can you do "greater than" and "less than" comparisons with floating point numbers?

    Is this valid?...


    No, it's not. That will have the propeller performing operations on the 32 bit binary representation of those floats.
    There are some comparison functions in the float32 library that will do what you require.

    I spent about 25 minutes chasing a bug on Friday where I was scaling a reading from a sensor and the result was garbage. All my calcs were fixed point and simply scaled to get resolution, and I'd put 12.2 instead of 122 into one of the calculations. 12.2 == $41433333 so things went birko. Of course it's legal, so it compiled and ran. I've been meaning to have the compiler warn you when using a float number in a naked expression like that...

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    lt's not particularly silly, is it?
  • localrogerlocalroger Posts: 3,452
    edited 2009-10-25 14:44
    Actually, except for a few special cases you can do integer comparisons of floating point numbers; the format is arranged so that the exponent is in the higher order bits for this very reason. If the exponents are different, since the exponents are in the high bits the larger exponent will test greater in an integer comparison; if the exponents are the same the number with the greater mantissa will rule. And the sign bit is out in front just as in integer math so that if one is number is negative and the other positive things will fall out properly. Note that this does assume neither number is a NaN, and that the numbers are properly normalized.
  • John AbshierJohn Abshier Posts: 1,116
    edited 2009-10-25 15:05
    The funciton you need is FCmp(a,b)
    From memory, need to check, returns -1 if a < b, 0 if a = b and 1 if a > b

    John Abshier
  • localrogerlocalroger Posts: 3,452
    edited 2009-10-25 15:19
    If you look at the source code for FCmp() you will notice that after manually testing the signs and plus/minus zero, it performs a simple integer comparison.
Sign In or Register to comment.