0

I am building a for loop using Euler's method for differential equations. The for loop however is not incrementing and only displaying the values for i=0 and not i=1 or i=2.

I have tried manually assigning all arguments and reconstructed the for loop.

import math

def Euler(a,b,N,alpha):
    h=(b-a)/N
    t=a
    w=alpha

    for i in range (0,N):
        w=w+h*(math.exp(t-w))
        t=a+(i*h)
        return t,w    
Euler(0,1,2,1)

I expect the function to return results for i=1 and i=2

3
  • 5
    your return is inside the for loop. (did you meant to put print there instead?)
    – pault
    Commented Apr 10, 2019 at 18:26
  • 1
    What's the result you expected?
    – Aran-Fey
    Commented Apr 10, 2019 at 18:26
  • 3
    return exits the function immediately, so your loop only executes once. Commented Apr 10, 2019 at 18:27

2 Answers 2

1

As pault mentioned in the comments, your return is inside the loop, which means the function exits on the first iteration.

What you probably want is yield, which would turn the function into a generator:

import math

def Euler(a,b,N,alpha):
    h=(b-a)/N
    t=a
    w=alpha

    for i in range (0,N):
        w=w+h*(math.exp(t-w))
        t=a+(i*h)
        yield t,w

for x, y in Euler(0,1,2,1):
    print(x, y)

>>> 0.0 1.1839397205857212
>>> 0.5 1.3369749844848988
2
  • What exactly does x,y represent in the second for loop? Commented Apr 11, 2019 at 3:31
  • @BickenBackBeingBoolean The Euler function/generator yields a tuple (yield t, w). Doing the for x, y in ... unpacks the tuple into two loop variables, instead of having to index a single loop variable (like x[0] or x[1]).
    – b_c
    Commented Apr 12, 2019 at 13:23
0

Your return is in the for loop. Unindent return once.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.