Python连接两点时如何控制曲率

2024-04-18 22:22:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一条原始曲线。我正在开发一个与原始曲线非常匹配的模型曲线。一切正常,但不匹配。如何控制模型曲线的曲率?下面的代码基于answer here。你知道吗

我的代码:

def curve_line(point1, point2):
    a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0]))
    b = point1[1] - a*np.sinh(point1[0])
    x = np.linspace(point1[0], point2[0],100).tolist()
    y = (a*np.cosh(x) + b).tolist()
    return x,y
###### A sample of my code is given below
point1 = [10,100]
point2 = [20,50]
x,y = curve_line(point1, point2)

plt.plot(point1[0], point1[1], 'o')
plt.plot(point2[0], point2[1], 'o')
plt.plot(x,y)  ## len(x)

我目前的产出:

enter image description here

我也尝试了以下功能:

y = (50*np.exp(-x/10) +2.5)

输出为:

enter image description here


Tags: 代码answer模型hereplotnplineplt
1条回答
网友
1楼 · 发布于 2024-04-18 22:22:10

不只是猜测模型函数的正确参数,您可以使用curve_fit将模型曲线拟合到数据中。你知道吗

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

x = np.array([ 1.92, 14.35, 21.50, 25.27, 27.34, 30.32, 32.31, 34.09, 34.21])
y = np.array([8.30, 8.26, 8.13, 7.49, 6.66, 4.59, 2.66, 0.60, 0.06])

def fun(x, a, b, c):
    return a * np.cosh(b * x) + c
coef,_ = curve_fit(fun, x, y)

plt.plot(x, y, label='Original curve')
plt.plot(x, fun(x, *coef), label=f'Model: %5.3f cosh(%4.2f x + %4.2f)' % tuple(coef) )
plt.legend()
plt.show()

enter image description here

如果密切拟合起点和终点很重要,则可以将不确定性传递给curve_fit,将其调整为接近终点的较低值,例如

s = np.ones(len(x))
s[1:-1] = s[1:-1] * 3
coef,_ = curve_fit(fun, x, y, sigma=s)

enter image description here

您的另一种方法a * np.exp(b * x) + c也会起作用,并给出-0.006 exp(0.21 x + 8.49)。你知道吗

在某些情况下,您必须对系数的初始值提供有根据的猜测,以curve_fit(它使用1作为默认值)。你知道吗

相关问题 更多 >