有1条曲线,我想找到经过这个曲线过零点的所有点。python示例代码
import numpy as np
import matplotlib.pyplot as plt
# 假设这是你的曲线数据
x = np.linspace(-10, 10, 1000) # 生成x轴的值
y = np.sin(x) # 生成y轴的值,即曲线的值
# 找到y值符号变化的位置
## np.sign() 如果数组值大于0则返回1,如果数组值小于0则返回-1,如果数组值为0则返回0
## np.diff() 差分
sign_changes = np.where(np.diff(np.sign(y)))[0] # eg: array([ 28, 185, 342, 499, 656, 813, 970], dtype=int64)
# 过零点的x坐标
zero_crossings_x = x[sign_changes] # array([-9.43943944, -6.2962963 , -3.15315315, -0.01001001, 3.13313313, 6.27627628, 9.41941942])
# 由于过零点可能不会精确落在采样点上,我们可以通过线性插值来估计过零点的精确位置
zero_crossings_y = []
for i in sign_changes:
# 线性插值
zero_crossing = y[i] - (y[i+1] - y[i]) / (x[i+1] - x[i]) * y[i]
zero_crossings_y.append(zero_crossing)
# 打印结果
print("过零点的x坐标:", zero_crossings_x)
print("过零点的y坐标 (应接近0):", zero_crossings_y)
# 绘制曲线和过零点
plt.plot(x, y, label='Curve')
plt.scatter(zero_crossings_x, zero_crossings_y, color='red', label='Zero Crossings')
plt.axhline(0, color='black', linewidth=0.5)
plt.legend()
plt.show()
## 输出结果:
过零点的x坐标: [-9.43943944 -6.2962963 -3.15315315 -0.01001001 3.13313313 6.27627628
9.41941942]
过零点的y坐标 (应接近0): [0.02932150337482438, -2.8198199947780667e-07, 0.02312027717766069, -1.6716403914568412e-07, 0.016918687676300323, -1.485976876530043e-07, 0.010716883956857083]