Passing an equation into a function in Python?

Question:

I thought I’d try to code a Euler’s method problem into a recursive function, but I’d like to improve the reusablity of it by being able to pass in any arrangement of the x and y values for the statement. For example, in my code the equation is x + y / 7 but I’d like to be able to pass in an arbitrary equation such as (x ^ 2 + y ) / 2 or something to that effect.

Can I do that with numpy or is there a handwritten way I can implement that will do this?

The only thing I can think of is getting the equation via a string and converting/rebuilding the equation in the function to generate the results.

y = -4
x = 0
step = 1

def eulersMethod(y, x, step):
    y = y+step*(x+y/7.)
    if y < 7:
        tmp = eulersMethod(y, x+step, step)
        if tmp < 7:
            y = tmp
    return y

print(eulersMethod(y, x, step))
Asked By: Thom

||

Answers:

You can use a lambda:

y = -4
x = 0
step = 1


def eulers_method(func, y, x, step):
    y = y + step * func(x, y)
    if y < 7:
        tmp = eulers_method(func, y, x + step, step)
        if tmp < 7:
            y = tmp
    return y


func = lambda x, y: x + y / 7.0
print(eulers_method(func, y, x, step))

If the function needs to be a string, you can use eval (warning: it’s evil):

def eulers_method(func, y, x, step):
    y = y + step * eval(func)
    ...

func = "x + y / 7.0"
print(eulers_method(func, y, x, step))
Answered By: Selcuk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.