AstlyDichrar
AstlyDichrar

Reputation: 121

Is it possible to work with a variable before its creation?

I want to create a function that plots a 2-dimensional system of differential equations, but if I call the function with a parameter like 2*x + 3*y I'll obviously run into an exception because I have not defined x and y at the time of execution.

In code, I want to do something like this:

import numpy as np
import matplotlib.pyplot as plt

def streamplot(xdot, ydot, xxrange, yyrange):
    """Displays the stream plot of a two-dimensional system of equations."""
    x, y = np.meshgrid(np.arange(0,xxrange,1),np.arange(0,yyrange,1)
    plt.streamplot(x, y, xdot, ydot)
    plt.show()

but evidently xdot and ydot will depend on x and y which are not assigned yet. I think it should be possible to catch the exception Python will create when the function is executed and create these variables at that time, but there should be a simpler way of doing this, right?

Upvotes: 0

Views: 79

Answers (3)

Denziloe
Denziloe

Reputation: 8131

Here's taking what Jacques de Hooge said in his answer and I in the comments, but making it more specific to your code. Note how f can be any function from R^2 to R^2, and can be passed to your streamplot function.

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
    return x + y, x*y

def streamplot(f, x_min=0, x_max=1, y_min=0, y_max=1,
        x_num_divisions=100, y_num_divisions=100):

    """Displays the stream plot of a two-dimensional system of equations."""

    x, y = np.meshgrid(
        np.linspace(x_min, x_max, x_num_divisions),
        np.linspace(y_min, y_max, y_num_divisions)
    )
    xdot, ydot = f(x, y)
    plt.streamplot(x, y, xdot, ydot)
    plt.show()

streamplot(f)

enter image description here

Upvotes: 0

franksands
franksands

Reputation: 2023

If you are trying to describe math equations in python, you can try using simpy:

from sympy import *
x = Symbol('x')
y = Symbol('y')
x+y+x-y
>>>2*x

you could define xdot and ydot as simpy Symbols.

more details here: https://www.scipy-lectures.org/advanced/sympy.html

Upvotes: 0

Jacques de Hooge
Jacques de Hooge

Reputation: 7000

Looks like xdot and ydot are functions rather than variables. You can pass in functions as parameters to other functions:

import math

def applyTwice (f, x):
    return f (f (x))

print (applyTwice (math.sqrt, 16))

print (applyTwice (lambda x: 2 * x, 10))

'''
Output:
2.0
40
'''

Upvotes: 1

Related Questions