Skip to content

Instantly share code, notes, and snippets.

@voidc
Created April 14, 2015 17:21
Show Gist options
  • Save voidc/e29b9b17ea44c44f78ba to your computer and use it in GitHub Desktop.
Save voidc/e29b9b17ea44c44f78ba to your computer and use it in GitHub Desktop.
Java Interpolator
package interpolations;
public class Interpolator {
public static final Interpolation LIN = x -> x;
public static final Interpolation SQR = x -> LIN.interpolate(x) * x;
public static final Interpolation CUB = x -> SQR.interpolate(x) * x;
public static final Interpolation EXP = x -> Math.pow(2, x) - 1;
public static final Interpolation LOG = x -> Math.log(x + 1) / Math.log(2);
public static final Interpolation COS = x -> -0.5 * Math.cos(Math.PI * x) + 0.5;
public interface Interpolation {
/**
* @returns a y value between 0 and 1 for a given x value between 0 and 1
*/
public double interpolate(double x);
public default double interpolate(double xMin, double xMax, double yMin, double yMax, double x) {
return interpolate((x - xMin) / (xMax - xMin)) * (yMax - yMin) + yMin;
}
/**
* @return modyfies the function where f(0) = 0 and f(1) = 1 so that f(xMin) = yMax and f(xMax) = yMax
*/
public default Interpolation range(double xMin, double xMax, double yMin, double yMax) {
return x -> interpolate((x - xMin) / (xMax - xMin)) * (yMax - yMin) + yMin;
}
/**
* @return modyfies the function where f(xMin) = yMax and f(xMax) = yMax so that f(0) = 0 and f(1) = 1
*/
public default Interpolation trim(double xMin, double xMax, double yMin, double yMax) {
return x -> (interpolate(x * (xMin - xMax) + xMin) - yMin) / (yMax - yMin);
}
public default Interpolation advt() {
return x -> interpolate(x) * x;
}
public default Interpolation slope(double slope) {
return x -> interpolate(x) * slope;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment