Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET implementation: Double conversion in Math.Min(float, float)

Why does .Net implement the Math.Min(float, float) function like so:

public static float Min(float val1, float val2)
{
  if ((double) val1 < (double) val2 || float.IsNaN(val1))
    return val1;
  else
    return val2;
}

While I can see the use of IsNaN I don't understand why they convert to double when comparing the values. Isn't that slower than simply writing val < val 2? Especially if I wanted to use it to clamp a value to numbers without much precision like 0f or 1f.

Should I just go ahead and implement a custom math library which additionally also requires to have non NaN values to get the best performance or is that a waste of time?

public static float Min(float a, float b)
{
    return a < b ? a : b;
}
like image 684
stfx Avatar asked Jan 17 '23 02:01

stfx


1 Answers

Yes, I used Resharper which does exactly that

And that's the problem, it fumbles the code. The source code is available from the Reference Source, it looks like this:

  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  public static float Min(float val1, float val2) {
    if (val1 < val2)
        return val1;

    if (Single.IsNaN(val1))
        return val1;

    return val2;
  }

Hard to guess why Resharper does this, I'd readily assume its just a bug. Favor the source code available from Microsoft, not just for accuracy but the comments are nice too.

like image 59
Hans Passant Avatar answered Jan 20 '23 17:01

Hans Passant