Python如何在连接两个点时控制曲率 [英] Python how to control curvature when joining two points

查看:248
本文介绍了Python如何在连接两个点时控制曲率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有原始曲线.我正在开发与原始曲线非常匹配的模型曲线.一切正常,但不匹配.如何控制模型曲线的曲率?以下代码基于在此处回答.

I have a original curve. I am developing a model curve matching closely the original curve. Everything is working fine but not matching. How to control the curvature of my model curve? Below code is based on 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)

我现在的输出:

我也尝试了以下功能:

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

输出为:

推荐答案

您不仅可以猜测模型函数的正确参数,还可以使用

Instead of just guessing the right parameters of your model function, you can fit a model curve to your data using 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()

如果很重要的一点是要紧密匹配起点和终点,您可以将不确定性传递给curve_fit,将其调整为朝着终点的较低值,例如由

If it is important that the start and end points are closely fitted, you can pass uncertainties to curve_fit, adjusting them to lower values towards the ends, e.g. by

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

您的其他方法a * np.exp(b * x) + c也将起作用并给出-0.006 exp(0.21 x + 8.49).

Your other approach a * np.exp(b * x) + c will also work and gives -0.006 exp(0.21 x + 8.49).

在某些情况下,您必须对curve_fit的系数的初始值提供有根据的猜测(默认使用1).

In some cases you'll have to provide an educated guess for the initial values of the coefficients to curve_fit (it uses 1 as default).

这篇关于Python如何在连接两个点时控制曲率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆