1 package net.sf.openrocket.util;
3 import java.util.Iterator;
5 import java.util.TreeMap;
7 public class LinearInterpolator implements Cloneable {
9 private TreeMap<Double, Double> sortMap = new TreeMap<Double,Double>();
12 * Construct a <code>LinearInterpolator</code> with no points. Some points must be
13 * added using {@link #addPoints(double[], double[])} before using the interpolator.
15 public LinearInterpolator() {
19 * Construct a <code>LinearInterpolator</code> with the given points.
21 * @param x the x-coordinates of the points.
22 * @param y the y-coordinates of the points.
23 * @throws IllegalArgumentException if the lengths of <code>x</code> and <code>y</code>
25 * @see #addPoints(double[], double[])
27 public LinearInterpolator(double[] x, double[] y) {
33 * Add the point to the linear interpolation.
35 * @param x the x-coordinate of the point.
36 * @param y the y-coordinate of the point.
38 public void addPoint(double x, double y) {
43 * Add the points to the linear interpolation.
45 * @param x the x-coordinates of the points.
46 * @param y the y-coordinates of the points.
47 * @throws IllegalArgumentException if the lengths of <code>x</code> and <code>y</code>
50 public void addPoints(double[] x, double[] y) {
51 if (x.length != y.length) {
52 throw new IllegalArgumentException("Array lengths do not match, x="+x.length +
55 for (int i=0; i < x.length; i++) {
56 sortMap.put(x[i],y[i]);
62 public double getValue(double x) {
63 Map.Entry<Double,Double> e1, e2;
67 e1 = sortMap.floorEntry(x);
70 // x smaller than any value in the set
71 e1 = sortMap.firstEntry();
73 throw new IllegalStateException("No points added yet to the interpolator.");
79 e2 = sortMap.higherEntry(x1);
82 // x larger than any value in the set
90 return (x - x1)/(x2-x1) * (y2-y1) + y1;
94 public double[] getXPoints() {
95 double[] x = new double[sortMap.size()];
96 Iterator<Double> iter = sortMap.keySet().iterator();
97 for (int i=0; iter.hasNext(); i++) {
104 @SuppressWarnings("unchecked")
106 public LinearInterpolator clone() {
108 LinearInterpolator other = (LinearInterpolator)super.clone();
109 other.sortMap = (TreeMap<Double,Double>)this.sortMap.clone();
111 } catch (CloneNotSupportedException e) {
112 throw new BugException("CloneNotSupportedException?!",e);