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

29 Views Asked by At

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?

2

There are 2 best solutions below

0
rochard4u On BEST ANSWER

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
1
Daraan On

This is because numpy arrays are not compatible with the math module.

The following will work and you will get a (324, 324) output


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

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

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

As a note math does work with single element arrays, hence the origin of this error:

math.sin(np.arange(1)) # -> 1
math.sin(np.arange(2)) # -> TypeError only size-1 arrays can be converted to Python scalars