# Easy Linear Interpolation?

Hey guys, recently my team has been pushing me to try to make our bot’s shooter able to make shots from any distance. I was able to accomplish this last year using LabVIEW’s built-in Linear Interpolation VI, but since last year we have moved to Java. If anyone out there could explain how to interpolate things in Java, that would be awesome!
Thanks

2 Likes
1 Like

Hopefully the code copies ok as I’m on my phone, this is the simple class 1706 made for use this year. This is not the most efficient for large table sizes (need to implement binary search) but it worked for us just fine for tables we used (up to 12pts).

``````package frc.robot.Utilities;

import java.awt.geom.Point2D;

/* This should be updated to use binary search at  some point */

public class LinearInterpolationTable {
private double m_maxInput =
Double.NEGATIVE_INFINITY;
private double m_minInput =
Double.POSITIVE_INFINITY;
private final Point2D[] m_points;
public final int size;

public LinearInterpolationTable(Point2D... points){
m_points = points;
size = m_points.length;
for(int i = 0;i<size;i++){
if(m_points[i].getX()>m_maxInput){
m_maxInput = m_points[i].getX();
}
if(m_points[i].getX()<m_minInput){
m_minInput = m_points[i].getX();
}
}

}

public double getOutput(double input){
int index = 0;
if(input <= m_minInput){
index = 0;
}
else if(input >= m_maxInput){
index = size-2;
}
else{
for(int i=1;i<m_points.length;i++){
if(input > m_points[i-1].getX() && input <= m_points[i].getX()){
index = i-1;
}
}
}
return interpolate(input, m_points[index], m_points[index+1]);
}

public static double interpolate(double input, Point2D point1, Point2D point2){
final double slope = (point2.getY()-point1.getY())/(point2.getX()-point1.getX());
final double delta_x = input - point1.getX();
final double delta_y = delta_x*slope;
return point1.getY()+delta_y;
}

public double[] getX(){
double[] xVals = new double[size];
for(int i = 0;i<size;i++){
xVals[i] = m_points[i].getX();
}
return xVals;
}
public double[] getY(){
double[] yVals = new double[size];
for(int i = 0;i<size;i++){
yVals[i] = m_points[i].getY();
}
return yVals;
}
public Point2D[] getTable(){
return m_points;
}
``````

}

2 Likes

You can have a look at Team254 , Team2910 and Team503’s code about interpolation. Their code are all in Java and you can use them as a lib. If you want to know how they are used, you can also take a look at their robot code ( l recommand you to have look at Team503 Frog Force and Team2910 Jack In the Bot’s interpolation related code if you are not very familiar with 254’s code structure.)

1 Like

There’s also this from wpilib

1 Like