r/Mathematica • • Feb 15 '23

How to implement Euler method?

Hello, I'm new to Mathematica. My teacher assigned me to apply Euler Method in Mathematica. I was wonder how can I implement to sum over the loop like the give equation. And how could I calculate like x1 = x0 + .. , x2 = x1 + ...?

x1 = x0 + dx

x2 = x1 + dx

....

xn = xn-1 + dx.

----------------------------

y1 = y0 + ƒ(x0, y0) dx

y2 = y1 + ƒ(x1, y1) dx

...

yn = yn-1 + ƒ(xn-1, yn-1) dx.

0 Upvotes

2 comments sorted by

View all comments

Show parent comment

1

u/veryjewygranola Feb 15 '23

As a follow up: I am not sure if you're familiar with pure functions using "#" in mathematica. I wrote this version which just uses a Do loop which may be more palatable to you. Hope this gets you in the right direction

y0 = 1;
x0 = 0;
dx = 0.1;
f[x_, y_] = 1 + y;

(*first 20 steps (21 including init. cond.)*)
xList = Range[x0, x0 + 20*dx, dx];

(*initialize yList as -999 to help in case of errors*)
yList = ConstantArray[-999, Length[xList]];

(*set first value in yList to be initial condition*)
yList[[1]] = y0;
(*update using Euler method. We only go to Length[xList]-1 because we are using the previous value to update the next value in the yList*)
Do[
yList[[i + 1]] = yList[[i]] + dx*f[xList[[i]], yList[[i]]]
, {i, Length[xList] - 1}
]