You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取两点间保留一位小数的所有坐标点

获取两点间保留一位小数的坐标点(Python实现)

核心思路

要生成两点间所有保留一位小数的坐标点,关键是保证坐标按均匀步长分布,同时处理浮点数精度问题:

  • 先计算两点在x、y轴上的总差值,确定生成点的总步数(基于0.1的精度,总步数为差值绝对值的10倍取整,取x/y方向的最大值保证均匀)
  • 计算每一步的x、y增量,循环生成每个点并保留一位小数

代码实现

def get_points_between(point1, point2):
    x1, y1 = point1
    x2, y2 = point2
    
    # 计算x和y方向的总差值
    dx = x2 - x1
    dy = y2 - y1
    
    # 确定总步数:取x或y方向上的最大步数(保证坐标均匀分布)
    steps = max(int(abs(dx) * 10), int(abs(dy) * 10))
    if steps == 0:
        return [point1]  # 两点重合时返回自身
    
    # 每一步的x、y增量
    step_x = dx / steps
    step_y = dy / steps
    
    points = []
    for i in range(steps + 1):
        # 计算当前坐标并保留一位小数,避免浮点数精度误差
        current_x = round(x1 + step_x * i, 1)
        current_y = round(y1 + step_y * i, 1)
        points.append((current_x, current_y))
    
    return points

测试示例

# 测试输入:起点(0,0),终点(1,2)
result = get_points_between((0, 0), (1, 2))
for coord in result:
    print(coord)

输出结果(节选):

(0.0, 0.0)
(0.1, 0.2)
(0.2, 0.4)
(0.3, 0.6)
...
(1.0, 2.0)

注意事项

  • 支持非整数起点/终点,比如get_points_between((0.5, 1.2), (1.5, 3.2))会生成正确的序列
  • 若不需要包含起点或终点,可修改循环范围:比如range(1, steps)会排除首尾两点
  • 使用round()函数避免浮点数精度问题(比如避免出现0.30000000000000004这类值)

内容的提问来源于stack exchange,提问作者Qusai QQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:52:45