matplotlib 如何求多项式的系数

omtl5h9j  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个数据集,我绘制和拟合曲线与以下代码。

import numpy as np
import matplotlib.pyplot as plt

R= -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2,  0.0,  0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6
power = 486.040152, 343.466487, 233.706048, 151.069770, 90.792498, 48.455720, 20.748440, 5.267210, 0.080000, 5.267210, 20.748440, 48.455720, 90.792498, 151.069770, 233.706048, 343.466487, 486.040152
p = np.polyfit(R, power, 4) #define polynomial
f = np.poly1d(p) #define function
plt.plot(R, power, '<', color="brown", fillstyle='none', label="R(T=1.23)", markersize=12) 
plt.plot(R, f(R), color="brown", linewidth=2.0)
plt.ylabel('Power', fontsize='20')
plt.xlabel('Distance', fontsize='20') 
plt.legend(framealpha=1, frameon=False, fontsize='16', loc=(0.4, 0.75), ncol=1, handletextpad=-0.4)

字符串
图看起来像这样,

然而,该曲线也可以表示为函数,

f(T, R) = (a1 * T^2) + (b1 * T^4) + (a2 * R^2) + (b2 * R^4) + (d * T^2 * R^2))


当给定以下值时,如何获得系数d(拟合曲线的单个值)?

a1 = -73.08,
b1 = 29.16,
a2 = 74.37,
b2 = 25.46,
T = 1.23

2izufjch

2izufjch1#

正如我在my answer to your previous question中所解释的,您可以使用scipy.optimize.curve_fit为特定函数创建拟合。在本例中,您希望优化单个参数,因此实际上可以只使用scipy.optimize.least_squares。和上次一样,雅可比行列式很容易计算。

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

plt.close("all")

R = np.array([-1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2,
             0.0,  0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6])
power = np.array([486.040152, 343.466487, 233.706048, 151.069770, 90.792498,
                  48.455720, 20.748440, 5.267210, 0.080000, 5.267210,
                  20.748440, 48.455720, 90.792498, 151.069770, 233.706048,
                  343.466487, 486.040152])

a1 = -73.08
b1 = 29.16
a2 = 74.37
b2 = 25.46
T = 1.23

def poly(R, a1, a2, b1, b2, T, d):
    return a1*T**2 + b1*T**4 + a2*R**2 + b2*R**4 + d*T**2*R**2

def func(d, R, power, a1, a2, b1, b2, T):
    return poly(R, a1, a2, b1, b2, T, d) - power

def jac(d, R, power, a1, a2, b1, b2, T):
    return np.array([T**2*R**2]).T

res = least_squares(func, 50, jac=jac, args=(R, power, a1, a2, b1, b2, T))
d = res.x[0]  # 50.37298613633045

plt.plot(R, power, '<', color="brown", fillstyle='none',
         label="R(T=1.23)", markersize=12)
plt.plot(R, poly(R, a1, a2, b1, b2, T, d), color="brown", linewidth=2.0)
plt.ylabel('Power', fontsize='20')
plt.xlabel('Distance', fontsize='20')
plt.legend(framealpha=1, frameon=False, fontsize='16',
           loc=(0.4, 0.75), ncol=1, handletextpad=-0.4)

字符串


的数据
拟合不是很好,但这是您设置的约束所能达到的最佳效果。

相关问题