package umontreal.iro.lecuyer.functions;

import java.util.Arrays;


/**
 * Represents a piecewise-constant function.
 * 
 */
public class PiecewiseConstantFunction implements MathFunction {
   private double[] x;
   private double[] y;


   /**
    * Constructs a new piecewise-constant function
    *  with X and Y coordinates given
    *  by x and y.
    * 
    * @param x the X coordinates.
    * 
    *    @param y the Y coordinates.
    * 
    * 
    */
   public PiecewiseConstantFunction (double[] x, double[] y) {
      if (x.length != y.length)
         throw new IllegalArgumentException();
      this.x = x.clone ();
      this.y = y.clone ();
   }


   /**
    * Returns the X coordinates of the function.
    * 
    * @return the X coordinates of the function.
    * 
    */
   public double[] getX() {
      return x.clone ();
   }


   /**
    * Returns the Y coordinates of
    *  the function.
    * 
    * @return the Y coordinates of the function.
    * 
    */
   public double[] getY() {
      return y.clone ();
   }


   public double evaluate (double x) {
      final int idx = Arrays.binarySearch (this.x, x);
      if (idx >= 0)
         return y[idx];
      final int insertionPoint = -(idx + 1);
      return y[insertionPoint];
   }
}

 

Ads help maintain this website.