已知两个点的坐标,这个两个点可以连成一条直线,目前在这条直线上按照固定距离进行插值,即增加更多点在这条直线上。
package com.demo.utils;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 两点插值计算
*
* @author elinx
* @since 2021-09-24 14:05
*/
public class PointInterUtil {
@Data
public static class Point {
private double x;
private double y;
}
public static List<Point> interpolation(Point prePoint, Point curPoint) {
double x0 = prePoint.getX();
double y0 = prePoint.getY();
double x1 = curPoint.getX();
double y1 = curPoint.getY();
double nDisX = Math.abs(x1 - x0);
double nDisY = Math.abs(y1 - y0);
List<Point> pointList = new ArrayList<>();
double stepLength = 1.0;
double rate = 1.0;
if (nDisX >= nDisY) {
//如果x轴方向距离较远,则以x轴坐标计算步长
if (x0 > x1) {
stepLength = -stepLength;
}
double xTemp = x0 + stepLength;
for (; x0 > x1 ? xTemp > x1 : xTemp < x1; xTemp += stepLength) {
double yTemp = rate * (y1 - y0) / (x1 - x0) * (xTemp - x0) + y0;
Point point = new Point();
point.setX(xTemp);
point.setY(yTemp);
pointList.add(point);
}
} else {
//如果y轴方向距离较远,则以y轴坐标计算步长
if (y0 > y1) {
stepLength = -stepLength;
}
double yTemp = y0 + stepLength;
for (; y0 > y1 ? yTemp > y1 : yTemp < y1; yTemp += stepLength) {
double xTemp = rate * (yTemp - y0) * (x1 - x0) / (y1 - y0) + x0;
Point point = new Point();
point.setX(xTemp);
point.setY(yTemp);
pointList.add(point);
}
}
return pointList;
}
}
二维平面上的线性插值算法实现
该博客介绍了如何在Java中实现基于两点的线性插值算法,用于在两点确定的直线上生成一系列等间距的点。首先计算两点之间的x轴和y轴距离,然后根据较远方向的坐标计算步长,并进行插值计算,生成新的点并存储到列表中。此算法适用于图形绘制、数据平滑等场景。
7288

被折叠的 条评论
为什么被折叠?



