-1

I made a Runge and Kutta algorithm to solve differential equations of the type dy/dx=f (x,y).

Instead of having a def f(x,y) in my code, I would like to enter it in the arguments of my Runge and Kutta function like know RK4 (x0,y0,xmax,f (x,y)).

How should I write it to make it work ?

I think it must be something like float(...) but I do not know at all...

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
John
  • 3
  • 1
  • Are you looking for anonymous functions? Check section 4.7.5. Lambda Expressions at https://docs.python.org/3/tutorial/controlflow.html! – Zafi Dec 16 '16 at 08:41
  • I am not such good friend with python. I just started learning it 3 weeks ago. So I don't really know if that section you sent me will help. Maybe it is called anonymous function but to me it is unknown. To give an example, my algorithm sovle the equation for a given derivative. But I would like to enter the mathematical formula of the derivative into the parameters of my algorithm, so I don't have to edit my file every time. – John Dec 16 '16 at 12:39
  • Would you like to enter the mathematical formula as some kind of string parameter or as a function parameter (where the mathematical formula is written in python). In the second case you should use lambda expressions. – Zafi Dec 16 '16 at 12:59
  • For what it's worth, I think the on hold reason is incorrect. I think your question is clear: how can I turn this algorithm into a program? Unfortunately the "Too Broad" close reason still applies. You can't just post a requirement and ask us to implement it for you. You need to take some time to learn Python, at least make an attempt as solving the problem yourself, then come back when you have a more specific question. – skrrgwasme Dec 16 '16 at 14:44
  • You can pass the function name as parameter. See https://stackoverflow.com/questions/15545383/howto-pass-a-function-to-a-function-in-python for a very similar question. – Lutz Lehmann Dec 16 '16 at 18:51

1 Answers1

0

Using lambda functions you could do something as the following:

def foo(x, y, bar ):
    return bar(x,y)

custom_func = lambda u,v: u**2+v
print(foo(2,1,custom_func))

Although I am not quite sure whether this is what you require exactly. The question is somewhat unclear to me.

Zafi
  • 619
  • 6
  • 16
  • So for instance I want to solve dY/dt=-Y. So I used Runge and Kutta algorithm RK (x0,xmax,yo) and in my Programm I have somewhere written defined a function f as -Y. So my program runs for that equation only. So my question is, if my equation is dY/dt=F (x,y,t), what should I write in my code to put F as a parameter i.e. RK(x0,xmax,y0,F). (And during calculation, the code would be able to F for several values of x, y and t.). Is your lambda doing that ? (Sorry for my English I am French) – John Dec 16 '16 at 17:17
  • You can call the lambda function custom_func with any any argument you like, yeah. – Zafi Dec 19 '16 at 08:51