typeerror for function defined


I am trying to plot a 2D heat map of the function/surface but it is throwing me the type error which I am unable to resolve..

from numbers import Real
from numpy.lib.type_check import real

x = np.linspace(-2,2, num=40, endpoint=True, retstep=False, dtype=None, axis=0)
y = np.linspace(-2,2, num=40, endpoint=True, retstep=False, dtype=None, axis=0)
def goldstein_func(x,y):
  z = (1+(x+y+1)**2*(19-14*x+3*x**2-14*y+6*x*y+3*y**2))*(30+(2*x-3*y)**2*(18-32*x+12*x**2+48*y-36*x*y+27*y**2))
  m = np.array(x,y)

plt.imshow(goldstein_func(x,y), 4)

**The above code throw in an error below:

TypeError Traceback (most recent call last)

—-> 2 plt.imshow(goldstein_func(x,y), 4)
3 plt.show()

in goldstein_func(x, y)

 10   z = (1+(x+y+1)**2*(19-14*x+3*x**2-14*y+6*x*y+3*y**2))*(30+(2*x-3*y)**2*(18-32*x+12*x**2+48*y-36*x*y+27*y**2))

—> 11 m = np.array(x,y)

TypeError: Cannot construct a dtype from an array**

I tried to fix the type-error

>Solution :

It appears that an issue is happening when attempting to construct a NumPy array with np.array(x, y) inside the goldstein_func() function. The np.array() function needs one argument that symbolizes the components of the array or several arguments that symbolizes multiple arrays to be combined. Nevertheless, in your code, you’re supplying two independent arguments, x and y, which is producing the TypeError.

To fix the mistake, you can use the np.meshgrid function to create 2-D arrays from the 1-D arrays x and y, and then pass these arrays into the goldstein_func to calculate the matching z values. Here’s the adjusted code:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2, 2, num=40, endpoint=True)
y = np.linspace(-2, 2, num=40, endpoint=True)
X, Y = np.meshgrid(x, y)

def goldstein_func(x, y):
  z = (1+(x+y+1)**2*(19-14*x+3*x**2-14*y+6*x*y+3*y**2))*(30+(2*x-3*y)**2*(18-32*x+12*x**2+48*y-36*x*y+27*y**2))
  return z

Z = goldstein_func(X, Y)
plt.imshow(Z, cmap='hot', extent=(-2, 2, -2, 2))

I hope this helps you out.

Leave a ReplyCancel reply