HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

What is the most pythonic way to solve a differential equation using the Euler method?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonicthewhatmethodwaysolvedifferentialusingeulerequation

Problem

For example, with this differential equation, how can I do it in a pythonic way?

dx/dt=f(x,t)


I have a way to do it, but I think this is not the most pythonic way:

import numpy as np
dt=0.01
N_iter=10./dt
def f(x,t):
    return x**2*t#insert your favorite function here
x=np.zeros(N_iter)
for i in range(N_iter-1):
    x[i+1]=x[i]+dt*f(x[i],i*dt)

Solution

Using a for loop is not an unpythonic way at all. Instead, an Euler method could be implemented with a recursive function, but it not necessary and less optimized in Python.

However, methods for vectorizing recursive sequences are discussed on the numpy-discussion mailing-list. I encourage you to use structures like for loops in such situations. You will minimize the risk of errors by writing simple and concise codes.

Context

StackExchange Code Review Q#41580, answer score: 3

Revisions (0)

No revisions yet.