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

求解非线性方程组时出现Size-1数组错误的原因及解决方法

错误原因与修复方案

原代码

import numpy as np
import matplotlib.pyplot as plt

 g = plt.figure(1, figsize=(5,5))

delta = 0.025

x1,x2 = np.meshgrid(np.arange(-4,4.1,delta),np.arange(-4,4.1,delta))

f1 = math.sin(x1 + 1.5) - x2 - 2.9

f2 = math.cos(x2 - 2) + x1

plt.contour(x,y,f1,[0])
plt.contour(x,y,f2,[0])
plt.show()

报错信息

Cell In[19], line 1
----> 1 f1 = math.sin(𝑥1 + 1.5) - x2 - 2.9

TypeError: only size-1 arrays can be converted to Python scalars


Cell In[20], line 1
----> 1 f2 = math.cos(x2 - 2) + 𝑥1

TypeError: only size-1 arrays can be converted to Python scalars

错误原因

  • Python标准库的math模块函数仅支持**单个数值(标量)**运算,而x1、x2是通过np.meshgrid生成的多维NumPy数组,math.sin/math.cos无法直接处理数组类型输入,因此抛出类型错误。
  • 额外问题:代码未导入math模块;plt.contour调用时使用了未定义的变量x、y(实际应为x1、x2);g = plt.figure(1, figsize=(5,5))行首存在多余空格。

修复后的代码

import numpy as np
import matplotlib.pyplot as plt

g = plt.figure(1, figsize=(5,5))

delta = 0.025

x1, x2 = np.meshgrid(np.arange(-4, 4.1, delta), np.arange(-4, 4.1, delta))

# 用NumPy向量化函数替代math模块函数
f1 = np.sin(x1 + 1.5) - x2 - 2.9
f2 = np.cos(x2 - 2) + x1

# 修正contour的变量名
plt.contour(x1, x2, f1, [0])
plt.contour(x1, x2, f2, [0])
plt.show()

关键说明

NumPy提供了与math模块对应的向量化函数(如np.sin、np.cos),这类函数可直接对整个NumPy数组的每个元素执行运算,无需手动遍历数组,这也是NumPy处理批量数值计算的核心优势。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:33:13