0

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?

jared
  • 4,165
  • 1
  • 8
  • 31
  • yes error is correct, `x1` and `x2` are `(324, 324)` numpy arrays. You cannot converted them to Python scalars by addition or subtraction. – Talha Tayyab Jul 21 '23 at 12:52

2 Answers2

1

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
Daraan
  • 1,797
  • 13
  • 24
0

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
rochard4u
  • 629
  • 3
  • 17