I am asked to code Backwards Euler for the given differential:
dy/dt = sin(3*t)-2*y , y0=1.2 ,x = [0 8]
I know that Euler Forward is:
y= y+h*(sin(3*t)-2*y)
and the general formula for Backwards Euler is:
y = y_i + h*y_i+1
I saw that for Backwards Euler,
y_i+1 = y_i / (1 + h)
so should my function be:
y_i+1 = sin(3*t)/(1+h)
y = y + h *sin(3*t)/(1+h)
Is this correct?
Thank you!
BE has the following numerical scheme: $y_{n+1}=y_n+h\cdot f(t_{n+1},y_{n+1})$.
Just consider $f(t,y)=\sin(3t)-2y$.
You'll get: $y_{n+1}(1+2h)=y_n+h\cdot \sin(3t_{n+1})$, and then
$y_{n+1}=\frac{y_n+h\cdot \sin(3t_{n+1})}{(1+2h)}$, where $y_0=1.2$.
$h$ is given by $h=\frac{N}{8}$, where $N$ is the number of discretization points
Note that this is a linear ODE, and then you can collect together the $y_{n+1}$-term. Otherwise, you should solve at each time-step a non-linear equation which defines implicitely $y_{n+1}$.
Anyway, your code will be just a for loop for $n$ which ranges from $1$ no $N$ and you can compute each $y_n$ with the expression above.
EDIT
As I wrote in the second(!) line, you have just to write the current expression for $f$ as a function of $t_{n+1},y_{n+1}$.
$y_{n+1}=y_n+h \cdot (\sin(3t_{n+1})-2y_{n+1})$
$y_{n+1}=y_n+h \cdot \sin(3t_{n+1})-2h \cdot y_{n+1})$
Now we need to write $y_{n+1}$ as a function of $y_n$, so we can compute explicitely at each time step $y_n$. So, we collect $y_{n+1}$.
$y_{n+1}+2 h \cdot y_{n+1}=y_n+h \cdot \sin(3t_{n+1})$
$y_{n+1}(1+2h)=y_n+h \cdot \sin(3t_{n+1})$
and hence, by dividing:
$y_{n+1}=\frac{y_n+h \cdot \sin(3t_{n+1})}{(1+2h)}$