从ex求(x,y)级数范德华方程的a和b

2024-04-26 09:53:11 发布

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

我需要用非线性平差来确定范德华方程中a和b的值。我对科学一无所知。我发现了scipy.optimize.curve\u fit曲线拟合用最小二乘法进行非线性调整,但我不确定我是否用对了。我已经查过了,但找不到能改变它的东西。你知道吗

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

r = 8.314472
t = 273

data = pd.read_excel("gases_data.xls", skiprows=2)

pressure = np.array(data.get(data.columns[0]))
hydrogen = np.array(data.get(data.columns[1]))
nitrogen = np.array(data.get(data.columns[3]))

def ff(L, a, b):
    return (r*t)/(L - b) - (a/L**2)

pfit, perr = curve_fit(ff,hydrogen,pressure)
y_fit = ff(hydrogen, *pfit)

plt.plot(hydrogen, pressure, "ro", label = "data")
plt.plot(hydrogen, y_fit, "b", label = "fit")

plt.text(10, 3, "a = " + str(pfit[0]) + "\nb = " + str(pfit[1]))

plt.legend()
plt.grid(True)

plt.show()

enter image description here

enter image description here


Tags: columnsimportdatagetasnppltscipy
1条回答
网友
1楼 · 发布于 2024-04-26 09:53:11

vanderwaals不是直线curve_fit的最佳函数。尝试增加传递给函数的参数(例如,创建雅可比矩阵并添加边界)

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

R = spc.R
T = spc.convert_temperature(0, 'C', 'K')


l_data = np.linspace(0.1, 20, 30)
a, b = 2.45e-2 , 26.61e-6

def P_vdw(L, a, b):
    return R * T / (L - b) - a / L**2

def jac(L, a, b):
    return np.array([-1 / L**2, R * T / (L - b)**2]).T

p_data = P_vdw(l_data, a * np.random.normal(1, 0.001, 30), b* np.random.normal(1, 0.001, 30))

plt.semilogy(l_data, p_data)
popt, popv = curve_fit(P_vdw, l_data, p_data, jac=jac,
                       bounds=[(1e-3, 1e-7), (1.0, 1e-6)],
                       method='trf')
plt.semilogy(l_data, P_vdw(l_data, *popt), 'ro')
print(popt)

相关问题 更多 >