NumPy数组中每两个连续点的线方程
Line equation of every two consecutive points in a NumPy array
我想求一个NumPy数组中每两个连续点(二维)的直线方程。我知道如何稳健地做到这一点(即使用循环),但我想知道是否有更复杂的方法。
谢谢。
下面给出了一个可靠的方法:
import numpy as np
a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
N = int(max(a.shape))
b = []
for i in range(N - 1):
x = [a[i,0], a[i + 1,0]]
y = [a[i,1], a[i + 1,1]]
b.append(tuple(np.polyfit(x, y, 1)))
print(b)
对于直线,请进行手写计算。 y = mx + c 其中 m 是梯度 = y 的变化/x 的变化,c 是常数 c = y0 - m*x0
import numpy as np
a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
x = a[:,0]
y = a[:,1]
dx = np.diff(x) # Change in x
dy = np.diff(y) # Change in y
# Amended for @Nan's comment below.
# If any dx is zero this will now return +-inf in m and c without raising a warning
# The code using m and c will need to handle this if it can occur.
with np.errstate( divide = 'ignore' ):
m = dy/dx # Gradient
c = y[1:] - m * x[1:] # Constant
m, c
# (array([ 2. , 4. , -3.5]), array([ 0. , -4. , 18.5]))
# y = mx + c
# Rerunning with x=3 x=3
a = np.array([[1, 2], [2, 4], [3, 8], [3, 12]])
m, c
(array([ 2., 4., inf]), array([ 0., -4., -inf]))
我想求一个NumPy数组中每两个连续点(二维)的直线方程。我知道如何稳健地做到这一点(即使用循环),但我想知道是否有更复杂的方法。
谢谢。
下面给出了一个可靠的方法:
import numpy as np
a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
N = int(max(a.shape))
b = []
for i in range(N - 1):
x = [a[i,0], a[i + 1,0]]
y = [a[i,1], a[i + 1,1]]
b.append(tuple(np.polyfit(x, y, 1)))
print(b)
对于直线,请进行手写计算。 y = mx + c 其中 m 是梯度 = y 的变化/x 的变化,c 是常数 c = y0 - m*x0
import numpy as np
a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
x = a[:,0]
y = a[:,1]
dx = np.diff(x) # Change in x
dy = np.diff(y) # Change in y
# Amended for @Nan's comment below.
# If any dx is zero this will now return +-inf in m and c without raising a warning
# The code using m and c will need to handle this if it can occur.
with np.errstate( divide = 'ignore' ):
m = dy/dx # Gradient
c = y[1:] - m * x[1:] # Constant
m, c
# (array([ 2. , 4. , -3.5]), array([ 0. , -4. , 18.5]))
# y = mx + c
# Rerunning with x=3 x=3
a = np.array([[1, 2], [2, 4], [3, 8], [3, 12]])
m, c
(array([ 2., 4., inf]), array([ 0., -4., -inf]))