code: private static double clamp(double d, double min, double max)
      {
          if (d < min)
          {
              return min;
          }
          if (d > max)
          {
              return max;
          }
          return d;
      }
docs: Clamp the given value to be in [min,max]
  
  @param d The value
  @param min The minimum value
  @param max The maximum value
  @return The clamped value