6
\$\begingroup\$

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)
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 13, 2014 at 19:14
\$\endgroup\$
4
  • 2
    \$\begingroup\$ What was wrong with scipy.integrate? \$\endgroup\$ Commented Feb 13, 2014 at 20:50
  • \$\begingroup\$ What makes you think the code isn't Pythonic? (apart from PEP8 issues) \$\endgroup\$ Commented Feb 14, 2014 at 10:25
  • \$\begingroup\$ Well I thought that there was only one pythonic way to do something and I was wondering if I was doing it right. The problem with 'scipy.integrate' is that I must do each step in turn inside a loop. \$\endgroup\$ Commented Feb 14, 2014 at 16:01
  • 1
    \$\begingroup\$ @NunoCalaim: Have you looked at scipy.integrate.odeint? \$\endgroup\$ Commented Feb 19, 2014 at 13:46

1 Answer 1

3
\$\begingroup\$

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.

answered Mar 13, 2014 at 4:17
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.