plotting 3d equation

79 Views Asked by At

I am trying to plot a 3d equation in python, but I am facing a type error: only size-1 array can be converted into scalars. The equation is:

$$z=f(x,y)=\cos(x)\cdot\cos(y)\cdot e^{(\frac{-\sqrt{(x^{2}+y^{2})}}{4})}$$

My Code is:

import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d.axes3d import Axes3D
import math

def f(x,y):
    return math.cos(x)*math.cos(y)*math.e**(-math.sqrt(x**2 + y**2)/4)
x_5 = np.linspace(start=-2, stop=2, num=200)
y_5 = np.linspace(start=-2, stop=2, num=200)
x_5, y_5 = np.meshgrid(x_5, y_5)
#plotting
fig = plt.figure(figsize=(16, 15))
ax = fig.add_subplot(111, projection="3d")
ax.set_xlabel("X", fontsize=18)
ax.set_ylabel("Y", fontsize=18)
ax.set_zlabel("z=f(X,Y), Cost Function", fontsize=18)
ax.plot_surface(x_5, y_5, f(x_5,y_5), cmap=cm.coolwarm, alpha=0.5)
plt.show()
1

There are 1 best solutions below

0
Nejc On

You need to use numpy functions, because math library can't handle arrays.

def f(x, y):
    return np.cos(x) * np.cos(y) * np.exp(-np.sqrt(x**2 + y**2) / 4)