0

I have the following equation: z*cos(theta)-x*sin(theta)=[A-B*[z*sin(theta)+x*cos(theta)]^2-B*y^2]

My Goal: I need the values of z, for a given range of x and y values on a square -40 to 40 for both x & y.

I'd like to solve this in python. I've noticed that there's a similar problem, but I need the value of z, not just the graph: Plot curve equation without solving for dependent variable in matplotlib? I'm not sure if matplotlib is doing some kind of optimization in order to find the values of y for that problem? If it's possible to extract the values of z directly from the plot that would be fine, however something is also wrong with my definition of this contour plot (I've made many contour plots when I knew what values I wanted on the Z-axis, but never when I didn't know how to solve for Z.

`theta = math.pi/12
A = scalar
B = scalar
step = 1
X, Y, Z = np.meshgrid(np.arange(-40,40,step), np.arange(-40,40,step), np.arange(-40,40,step))
plt.contour(X,Y, Z*np.cos(theta)-X*np.sin(theta), A-B*[Z*np.sin(theta)+X*np.cos(theta)]^2-B*Y^2)
plt.show()`

I'm not sure if I need a solver like scipy optimize, Fzero, or a crazy version of excel's solver? I noticed that Wolfram Alpha can plot a nice contour plot of the equation given values for theta, A, and B, but nonetheless it still doesn't provide me with values for z, given set values for x and y.

Thanks for your help,

Sean
  • 133
  • 1
  • 8

1 Answers1

0

You need to solve the equation to get Z.

I changed the range of x because we don't have the values of A and B. So, just change these values in the code.

import matplotlib.pyplot as plt
import numpy as np
from numpy import pi, sin, cos
from scipy.optimize import root

theta = pi/12
A = 1
B = 0.05
step = 1


def func(z, x, y):
    left_side = z*cos(theta)-x*sin(theta)
    right_side = A-B*(z*sin(theta)+x*cos(theta))**2-B*y**2
    return left_side - right_side


x = np.arange(40, 121, step)
y = np.arange(-40, 41, step)
X, Y = np.meshgrid(x, y)
nx = len(x)
ny = len(y)

z_guess = np.zeros((nx, ny))
args = (X, Y)
options = {'maxiter': 100}
ans = root(func, 
           z_guess, 
           args=args,
           tol=1.0e-5, 
           method='krylov',
           options=options)

Z = ans.x
success = ans.success
message = ans.message
f = func(Z, *args)
allclose = np.allclose(f, np.zeros((nx, ny)))
print("Success:", success)
print("Message:", message)
print("Is f(z, x, y) = zero by tolerance?:", allclose)
del(ans)

fig, ax = plt.subplots(figsize=(5, 5))
cont = ax.contourf(X, Y, Z, cmap='jet')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.colorbar(cont, label='z')
plt.show()

enter image description here

Joao_PS
  • 633
  • 1
  • 9