classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Problems with float Math.min(float,float) etc


From: Peter Dickerson
Subject: Problems with float Math.min(float,float) etc
Date: Tue, 15 Jan 2002 09:05:50 -0000

Math.min(float,float) seems to have incorrect behaviour for negative zero.

  public static float min(float a, float b) {
    if (a == 0.0f && b == 0.0f) // return -0.0f, if a or b is -0.0f
      return ((Float.floatToIntBits(a) >> 31) == 1) ? a : b;
    return (a < b) ? a : b;
  }

note that the condition (Float.floatToIntBits(a) >> 31) == 1 is never true
since int >> 31 can only be 0 or -1. So
    Math.min( -0.0f, 0.0f )
incorrectly returns 0.0f instead of -0.0f.

A releated problem affects min(double,double) and max.

Solution:
  public static float min(float a, float b) {
    if (a == 0.0f && b == 0.0f) // return -0.0f, if a or b is -0.0f
      return (Float.floatToIntBits(a) < 0) ? a : b;
    return (a < b) ? a : b;
  }

This also avoids multibit shifts which are slow on some processors (e.g.
Palm).

PS I don't understand how to report a bug via Savannah.
--
Peter.Dickerson (at) ukonline (dot) co (dot) uk






reply via email to

[Prev in Thread] Current Thread [Next in Thread]