具有涉及积分的函数的适合

问题描述 投票:0回答:2

我正在尝试使图形具有涉及积分的功能。如果我不使用np.array(),则会出现错误:“函数调用的结果不是正确的浮点数组。”而且,如果我使用np.array(),则会出现另一个错误:x和y必须具有相同的第一维,但形状为(501,)和(1,)。我该如何解决?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import sympy as sp


x1=[1,2,3,4,5]
y=[6,12,18,24,30]


x,a,t=sp.symbols('x a t')

def f(x,a):
    return np.array([sp.integrate(t*x*a,(t,0,2))],dtype=float)

xFit=np.arange(0,5.01,0.01)
popt, pcov=curve_fit(f,x1,y)
plt.scatter(x1,y)
plt.plot(xFit,f(xFit,*popt),color="r")
print(popt[0])
python sympy curve-fitting integral integrate
2个回答
0
投票

f(x,a)函数需要标量参数,并且即使x是向量也返回标量值。尝试用以下命令替换您的plot()行:

ystar = [f(_x, popt[0]) for _x in xFit]
plt.plot(xFit, ystar, color="r")

0
投票

嗯...在我看来,这已解决:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import sympy as sp


x1=[1,2,3,4,5]
y=[6,12,18,24,30]


x,a,t=sp.symbols('x, a, t', real=True)
g=sp.integrate(t*x*a,(t,0,2))
f=sp.lambdify((x,a),g)

xFit=np.arange(0,5.01,0.01)
popt, pcov=curve_fit(f,x1,y)
plt.scatter(x1,y)
ystar = [f(_x, popt[0]) for _x in xFit]
plt.plot(xFit, ystar, color="r")
print(popt[0])
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.