Search code examples
pythonnumpyjupyter-notebooknonlinear-equation

Size-1 array error when trying to solve system of nonlinear equations


Here is my code:

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()

When I run it, I get the following error:

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

Why is this happening and how can I fix it?


Solution

  • The sin and cos functions of the math module take scalars and you are providing matrices.

    Use the numpy version (that can take n-dimensional vectors) instead:

    f1 = np.sin(x1 + 1.5) - x2 - 2.9
    f2 = np.cos(x2 - 2) + x1