FastMath addition

Clamping. This could be added to fast math. I have needed it a fair bit in different circumstances. But again this is myself, who knows if anyone else needs it.


/**
    * Take a float and clamp it between 0.0 and 1.0
    *
    * @param input
    * @return clamped input
    */
   public static float clamp( float input ) {
      input = input < 0 ? 0 : input;
      input = input > 1 ? 1 : input;
      return input;
   }

Maybe it's faster to use Math.max / min instead?


return Math.max(Math.min(input, 1f), 0f);

It is faster to type but is about a magnitude slower.

Any insights on why it's so much slower? Maybe just a keyword i can feed to google to learn about that?

in that case i'd rather have a clamp(in, min, max)

Sounds good to me. Ill check the java source for min and max sometime and let ya know.

The Java version does a few more checks. Java.min and max both check to see if the number is valid ie not a NaN. Also it makes a difference between positive zero and negative zero. So it would seem it is slower due to the excessive checking and extra method call.



Any other insight most welcome.


   /**
    * Take a float and clamp it between min and max.
    *
    * @param input
    * @param min
    * @param max
    * @return clamped input
    */
   public static float clamp( float input , float min , float max ) {
      
      input = input < min ? min : input;
      input = input > max ? max : input;
      
      return input;
   }


   /**
   * Take a float and clamp it between min and max.
   *
   * @param input
   * @param min
   * @param max
   * @return clamped input
   */
   public static float clamp( float input , float min , float max ) {

      return (input < min) ? min : (input > max) ? max : input;

   }

Ok already…  clamp is in cvs :slight_smile:

:slight_smile: