You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用curve_fit()进行多项式拟合时遇类型错误求助

解决curve_fit()中的TypeError问题

我一眼就揪出问题啦——你在多项式函数里用了^符号,但在Python中,^是按位异或运算符,根本不是幂运算!你想要的三次方得用**来表示,这就是导致那个奇怪TypeError的核心原因。

来看看修正后的完整可运行代码:

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

def func(x, a, b, c, d):
    # 把错误的^换成Python的幂运算符号**
    return a*x**3 + b*x**2 + c*x + d

Xdata1 = np.array([10, 20, 30, 60])
Ydata1 = np.array([3, 5, 4, 3.5])

plt.plot(Xdata1, Ydata1, 'bo', label='Raw Data')
popt, pcov = curve_fit(func, Xdata1, Ydata1)
a, b, c, d = popt

# 生成更多x点让拟合曲线更平滑(可选但体验更好)
x_fit = np.linspace(min(Xdata1), max(Xdata1), 100)
plt.plot(x_fit, func(x_fit, *popt), 'r--', label='Fit')

plt.legend()
plt.show()

另外补充两个小细节:

  • 你的原代码里没导入numpy和matplotlib.pyplot,直接运行会报错,我已经补上了
  • 原代码用原始离散点画拟合线,看起来会很生硬,我加了linspace生成更多连续点,让拟合曲线更顺滑

这样修改后,就能正常运行并得到你想要的三次多项式拟合结果啦!

内容的提问来源于stack exchange,提问作者Riccardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:32:21