numpy - NumPy 数组中每两个连续点的线方程
问题描述
我想在 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]))
推荐阅读
- react-native - 将 expo-segment 与 facebook 应用程序事件集成不起作用
- python - 树视图单击选定的行
- java - 如何根据注释引发事件
- laravel - Laravel - 执行查询后追加连接查询
- caching - 通过将 cacheManager 迁移到构造函数注入,类不存在
- java - 错误类路径为空。请首先构建项目,例如通过运行 apache kafka
- python - Matplotlib 未对齐的值和图形名称
- reactjs - ReactJS Material-UI 如何将组件固定在锚定菜单之上
- android - READ_PHONE_STATE 权限似乎在 Android 11 中被主动拒绝
- sql - 错误语法错误:预期输入结束,但在 [19:10] 得到“(”