求解非线性方程组时出现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
相关产品推荐
相关产品推荐

