/// <summary> /// Compares two floating point values within a specified tolerance in ULPs. /// </summary> /// <param name="x">One floating point value to be compared.</param> /// <param name="y">Other floating point value to be compared.</param> /// <param name="tolerance">The tolerance for equality in terms of ULPs.</param> /// <param name="difference">The difference between the values in terms of ULPs.</param> /// <returns>0 if <paramref name="x"/> = <paramref name="y"/> ± <paramref name="tolerance"/> ULPs; +1 if x > y + tolerance ULPs; -1 if x < y - tolerance ULPs.</returns> /// <remarks> /// <list> /// <item> 0 if x = y ± tolerance ULPs</item> /// <item>+1 if x > y + tolerance ULPs</item> /// <item>-1 if x < y - tolerance ULPs</item> /// </list> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="tolerance"/> is negative or in excess of 2<sup>22</sup> (the limit of the significand in a single-precision floating point value).</exception> public static int Compare(float x, float y, int tolerance, out int difference) { // Make sure tolerance is non-negative and small enough that the // default NAN won't compare as equal to anything. const int maxSignificand = 4 * 1024 * 1024; // single-precision values has a 22-bit significand if (tolerance < 0 || tolerance >= maxSignificand) { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be in the range [0,2\u00B2\u00B2)"); } // Reinterpret float bits as sign-magnitude integers. int xi = BitReinterpreter.Convert(x); int yi = BitReinterpreter.Convert(y); // Convert from sign-magnitude to two's complement form, // by subtracting from 0x80000000. if (xi < 0) { xi = int.MinValue - xi; } if (yi < 0) { yi = int.MinValue - yi; } // How many epsilons apart? difference = xi - yi; // Is the difference outside our tolerance? if (xi > yi + tolerance) { return(+1); } if (xi < yi - tolerance) { return(-1); } else { return(0); } }
public static float Convert(int i) { BitReinterpreter br = new BitReinterpreter(i); return br.f; }
public static int Convert(float f) { BitReinterpreter br = new BitReinterpreter(f); return br.i; }
internal static float Convert(int value) { return(BitReinterpreter.Convert(value)); }
public static float Convert(int i) { BitReinterpreter br = new BitReinterpreter(i); return(br.f); }
public static int Convert(float f) { BitReinterpreter br = new BitReinterpreter(f); return(br.i); }