gpt4 book ai didi

python - 将 python 操作转换为 numpy

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:37 25 4
gpt4 key购买 nike

我编写了一个基本代码,它接受两个点坐标,导出穿过它的线和垂直线的方程,然后输出作为同一垂直线的边缘的两个点。我的目标是做像this answer图片中所示的事情,但没有所有这些第三方软件包,也没有 GIS。

现在,谈论性能,我认为我的代码可以极大地受益于 numpy 包,特别是考虑到在具有大量(甚至数百万)点坐标对的循环中使用此计算。由于我不太使用 numpy,任何人都可以:

  1. (确认调整代码以使用 numpy 可以提高性能)
  2. 建议我是否应该调整代码(例如一些好的开始提示)?

这是代码,希望有人会发现它有用(matplotlib 只是为了可视化结果)。

import matplotlib.pyplot as plt

# calculate y from X coord, slope and intercept
def calculate_y(x, m, q):
y = m * x + q
return y

# the two point coordinates
point_A = [5,7] # First considered point
point_B = [4,10] # Second considered point

# calculate the slope between the point pair
m = (point_A[1] - point_B[1]) / (point_A[0] - point_B[0])

# calculate slope and intercept of the perpendicular (using the second original point)
m_perp = -(1/m)
q_perp = point_B[1] - m_perp * point_B[0]
##print "Perpendicular Line is y = {m}x + {q}".format(m=m_perp,q=q_perp)

# calculate corods of the perpendicular line
distance_factor = 1 #distance from central point
min_X = point_B[0] - distance_factor # left-side X
min_Y = calculate_y(min_X, m_perp, q_perp) # left-side Y

max_X = point_B[0] + distance_factor # right-side X
max_Y = calculate_y(max_X, m_perp, q_perp) # right-side Y

perp_A = (min_X, min_Y)
perp_B = (max_X, max_Y)

x_coord, y_coord = zip(*[point_A, point_B])
x_perp_coord, y_perp_coord = zip(*[perp_A, perp_B])

plt.scatter(x_coord, y_coord)
plt.scatter(x_perp_coord, y_perp_coord)
plt.show()

最佳答案

1)是的,numpy 会大大提高性能。您无需在 Python 中执行循环,而是使用 numpy 的向量化在 C 中进行循环。

2)想法:

import matplotlib.pyplot as plt
import numpy as np

# get random coords
npts = 10
distance_factor = 0.05
points = (np.sort(np.random.random(2*npts)).reshape((npts,2)) \
+ np.random.random((npts,2))/npts).T
points_x = points[0] # vector of the chain of x coords
points_y = points[1] # vector of the chain of y coords
plt.plot(points_x, points_y, 'k-o')
plt.gca().set_aspect('equal')
points_x_center = (points_x[1:] + points_x[:-1])*0.5
points_y_center = (points_y[1:] + points_y[:-1])*0.5
plt.plot(points_x_center, points_y_center, 'bo')
ang = np.arctan2(np.diff(points_y), np.diff(points_x)) + np.pi*0.5
min_X = points_x_center + distance_factor*np.cos(ang)
min_Y = points_y_center + distance_factor*np.sin(ang)
max_X = points_x_center - distance_factor*np.cos(ang)
max_Y = points_y_center - distance_factor*np.sin(ang)
plt.plot(np.vstack((min_X,max_X)), np.vstack((min_Y,max_Y)), 'r-')
plt.plot(np.vstack((min_X,max_X)).T, np.vstack((min_Y,max_Y)).T, 'r-', lw=2)

关于python - 将 python 操作转换为 numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com