copySign function

double copySign(
  1. double magnitude,
  2. double sign
)

Returns the first argument with the sign of the second argument. A NaN sign argument is treated as positive.

magnitude the value to return. sign the sign for the returned value. Returns the magnitude with the same sign as the sign argument.

Implementation

double copySign(double magnitude, double sign) {
  // The highest order bit is going to be zero if the
  // highest order bit of m and s is the same and one otherwise.
  // So (m^s) will be positive if both m and s have the same sign
  // and negative otherwise.
  /*final long m = Double.doubleToRawLongBits(magnitude); // don't care about NaN
  final long s = Double.doubleToRawLongBits(sign);
  if ((m^s) >= 0) {
      return magnitude;
  }
  return -magnitude; // flip sign*/
  if (sign == 0.0 || sign.isNaN || magnitude.sign == sign.sign) {
    return magnitude;
  }
  return -magnitude; // flip sign
}