1. 直线插补基础实现
任务目标
实现从起点到终点的三维直线插补,输出插补点序列,并验证插补点沿直线等距分布。输入为起点坐标、终点坐标与插补步数,输出为包含起点和终点的等间距点列。
核心实现
import numpy as np
def linear_interpolate(start, end, steps):
"""
三维直线插补
:param start: 起点坐标 (x, y, z)
:param end: 终点坐标 (x, y, z)
:param steps: 插补段数(输出点数为 steps + 1)
:return: (steps+1, 3) 的插补点数组
"""
start = np.array(start, dtype=float)
end = np.array(end, dtype=float)
if steps < 1:
raise ValueError("steps 必须 ≥ 1")
# 生成 [0, 1] 区间内 steps+1 个等距参数
t = np.linspace(0.0, 1.0, steps + 1)
# 直线参数方程: P(t) = start + t * (end - start)
points = start + np.outer(t, end - start)
return points
def verify_uniform_spacing(points):
"""
验证相邻插补点间距是否相等
:return: (最大间距偏差, 平均间距)
"""
diffs = np.diff(points, axis=0)
distances = np.linalg.norm(diffs, axis=1)
mean_dist = np.mean(distances)
max_deviation = np.max(np.abs(distances - mean_dist))
return max_deviation, mean_dist
if __name__ == "__main__":
# 示例:从 (0,0,0) 到 (10,5,20),分 10 段
start = (0.0, 0.0, 0.0)
end = (10.0, 5.0, 20.0)
steps = 10
pts = linear_interpolate(start, end, steps)
print("插补点数:", len(pts))
print("起点:", pts[0])
print("终点:", pts[-1])
print("前3个插补点:")
for p in pts[:3]:
print(f" {p}")
dev, avg = verify_uniform_spacing(pts)
print(f"平均间距: {avg:.6f}")
print(f"最大间距偏差: {dev:.2e}")
assert dev < 1e-9, "等距验证失败"
print("等距验证通过")
运行与验证
环境依赖:仅需 Python 3 和 NumPy(pip install numpy)。
运行方式:将代码保存为 linear_interp.py,在终端执行 python linear_interp.py。
验证方法:
- 程序输出插补点总数应为
steps + 1 = 11,首点为起点(0,0,0),末点为终点(10,5,20)。 - 计算相邻点间欧氏距离,理论值为
||终点-起点|| / steps = 22.9129 / 10 ≈ 2.29129。程序输出平均间距应接近该值,最大间距偏差应小于1e-9(浮点精度范围内),并打印“等距验证通过”。
预期输出(示例):
插补点数: 11
起点: [0. 0. 0.]
终点: [10. 5. 20.]
前3个插补点:
[0. 0. 0.]
[1. 0.5 2. ]
[2. 1. 4. ]
平均间距: 2.291288
最大间距偏差: 0.00e+00
等距验证通过
该输出由代码逻辑直接唯一推出,非实测结果。若需验证其他起终点,修改 start、end、steps 变量后重新运行即可。