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

如何拆分Hilbert曲线坐标列表以适配Matplotlib绘图及点运算

解决Hilbert曲线点集的拆分与算术运算问题

核心问题说明

你不用np.split()或str.split()来拆分点集——hilbert_curve.points_from_distances()返回的本身就是元组组成的列表,每个元组对应一个二维坐标(比如(x, y))。直接对列表里的元组操作就行,之前的方法用错方向了。


1. 拆分点集用于Matplotlib绘制

提取所有点的x、y坐标,转成Matplotlib能识别的序列即可:

import matplotlib.pyplot as plt

# 用列表推导式提取坐标
x_coords = [point[0] for point in points]
y_coords = [point[1] for point in points]

# 绘制曲线(保持坐标轴比例一致避免变形)
plt.plot(x_coords, y_coords, linewidth=1)
plt.axis('equal')
plt.show()

也可以转成numpy数组,方便后续批量运算:

points_np = np.array(points)
x_coords = points_np[:, 0]  # 取所有行的第0列(x坐标)
y_coords = points_np[:, 1]  # 取所有行的第1列(y坐标)

2. 坐标算术运算(缩放、平移)

Hilbert曲线的坐标范围是[0, 2^p - 1](p是阶数),基于此做变换:

  • 缩放至1x1区域:把每个坐标除以最大值2^p - 1
  • 修改起始点:给所有坐标加上偏移量

示例代码:

max_coord = 2**p - 1

# 缩放至1x1区域
scaled_points = [(x/max_coord, y/max_coord) for x, y in points]

# 缩放后平移到(0.2, 0.2)为起点
offset_x, offset_y = 0.2, 0.2
translated_points = [(x + offset_x, y + offset_y) for x, y in scaled_points]

# numpy数组版本(更高效)
points_np = np.array(points)
scaled_np = points_np / max_coord
translated_np = scaled_np + np.array([offset_x, offset_y])

3. 验证特定点是否在曲线上

用hilbert_curve.distance_from_point()方法,若返回的距离在有效范围(0到totalpoints-1)内,则该点在曲线上:

def is_point_on_curve(target_point, hilbert_curve, total_points):
    try:
        dist = hilbert_curve.distance_from_point(target_point)
        return 0 <= dist < total_points
    except ValueError:
        # 坐标超出曲线范围时会抛出异常
        return False

# 示例:验证点(3,1)是否在p=2的曲线上
target = (3,1)
print(is_point_on_curve(target, hilbert_curve, totalpoints))  # 输出True

完整整合代码

把所有功能整合到你的代码中:

import numpy as np
from hilbertcurve.hilbertcurve import HilbertCurve
import matplotlib.pyplot as plt

def is_point_on_curve(target_point, hilbert_curve, total_points):
    try:
        dist = hilbert_curve.distance_from_point(target_point)
        return 0 <= dist < total_points
    except ValueError:
        return False

p = int(input("order of curve: "))
n = 2
hilbert_curve = HilbertCurve(p, n)
totalpoints = 2 ** (p * n)
distances = list(range(totalpoints))
points = hilbert_curve.points_from_distances(distances)

# 绘制原始曲线与变换后的曲线
points_np = np.array(points)
plt.figure(figsize=(8,4))

plt.subplot(121)
plt.plot(points_np[:,0], points_np[:,1], linewidth=1)
plt.title("Original Hilbert Curve")
plt.axis('equal')

max_coord = 2**p -1
scaled_translated = points_np / max_coord + np.array([0.1, 0.1])
plt.subplot(122)
plt.plot(scaled_translated[:,0], scaled_translated[:,1], linewidth=1)
plt.title("Scaled & Translated Curve")
plt.axis('equal')

plt.show()

# 验证点示例
target_point = (2**p -1, 0)
print(f"Point {target_point} is on curve: {is_point_on_curve(target_point, hilbert_curve, totalpoints)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:53:13