Floating point ( Greater than and Less than )
grasshopper
Posts: 438
I am always finding my self having to compare a floating point number with another floating point number to see if one is greater or less than the other. It seems that there has to be a better way of doing this than what I am currently doing.
I basically take both numbers and convert them into a non-floating number only to do the < > then converting them back to floating point. I ask if there is an object that has this built in feature? Perhaps I over looked something.
Thanks in advance.
I basically take both numbers and convert them into a non-floating number only to do the < > then converting them back to floating point. I ask if there is an object that has this built in feature? Perhaps I over looked something.
Thanks in advance.
Comments
if flt.fsub(a,b) < 0 ' Is a < b?
Unfortunately it is not if floatmath if you are using that library.
Mike, you need to elaborate on checking the sign of the result of subtration.· flt.fsub(a,b) < 0 will not work because flt.fsub(a,b) is a float and 0 is an integer and < only works· for integers.· One could check bit 31.
John Abshier
Post Edited (John Abshier) : 11/18/2008 3:22:26 PM GMT
If I understand Mike properly, he's exploiting the fact that signed 32-bit integers and 32-bit IEEE 754 floats use the same bit to store sign.
If the float is positive, the high bit will be zero. If the float is negative, the high bit will be 1. The remaining bits represent the exponent and mantissa of the floating point number.
If both high bits are zero, the larger integer is ALSO the larger floating point value. If the high bits are different, one is negative and one is positive, and the integer comparison is still valid.
If both high bits are one, the larger integer is the smaller value (the lower 31 bits are the absolute value of the number). This is the only case requiring special handling.
This code will not handle NANs or infinity correctly, but if your floats are known to be valid numbers it works fine. I've done list sorting on floats this way and it's significantly faster than using "real" float comparisons.
Thinking about it, it's quite possible that the assembly code in the Float32 object implements it exactly this way.
Jason