0

I have a an equation that i want to use as an argument in my function, the catch is i want to have it within my function without defining any of its variables. The idea is once have it inside my function i can manipulate the vars...sort of like a blank equation. Is this possible or am i being silly?

y = 79.94 + 0.99*var_1 + 0.52*var_2 -1.38*(var_1**2) -1*(var_2**2) + 0.25*var_1*var_2


def ctr_plt(y, x_min= -1, x_max= 1, x_pnts= 25, y_min= -1, y_max= 1, y_pnts= 25, plt1_lvl= 100, plt2_lvl= 5, fig_= 0):

x1 = np.linspace(x_min, x_max, x_pnts)
y1 = np.linspace(y_min, y_max, y_pnts)
var_1, var_2 = np.meshgrid(x1,y1)
    
fig = plt.figure(figsize=(10,6))

y = fun(var_1,var_2)

plt.subplot(1,2,1)
cntr_plt =plt.contourf(var_1,var_2, y, plt1_lvl, cmap='rainbow')

if fig_ > 0:
    
    plt.subplot(1,2,2)
    cntr_plt = plt.contour(var_1,var_2,y,plt2_lvl)#,colors='black', linestyles='dashed')
    cntr_plt =plt.contourf(var_1,var_2,y,plt2_lvl, cmap='rainbow')
    #plt.colorbar()
    plt.clabel(cntr_plt, inline=1, fontsize=12, colors='black')
    
hghebrem
  • 5
  • 2
  • You can use lambda functions: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions – RafazZ Aug 24 '22 at 01:34
  • 4
    Hello! Your code is incomplete and pretty unclear to me. Try creating a minimal example; something that is complete and can be run, and doesn't contain extra stuff like plotting / colors. https://stackoverflow.com/help/minimal-reproducible-example – Kirk Broadhurst Aug 24 '22 at 01:34
  • An equation is a function. Seems like you could make a function out of it, taking your vars as arguments, and you can pass it around, e.g. to other functions. – Matt Hall Aug 24 '22 at 01:37
  • I certainly think this is possible in Python, but I'm not sure if I fully understand your question, and I don't like to answer a question that's unclear. Could you update the question with a bit more details? Like an example of what you want to do (pseudo-code / Python code that is not currently working + the expected output)? That would make it much easier to answer this question. – wovano Oct 11 '22 at 05:34

1 Answers1

1

I'm not fully clear about your goal, but it sounds like a good use case for a symbolic math library like sympy.

Here is an example. If you clarify your question, we could tailor a more suitable example.

import sympy as sp
import sympy.plotting as spp

# Define symbols
x = sp.symbols("x")


# Create a function that works with symbolic expression
# In this example, we find the derivative of the expression and plot both
def plot_equation_and_derivative(eq):
    d1 = sp.diff(eq)
    spp.plot(eq, d1, (x, -10, 10))


# Application of function
plot_equation_and_derivative(x ** 2)
plot_equation_and_derivative(x ** 3)
plot_equation_and_derivative(sp.E ** x)