Euler Method in R

Euler Method
Euler's method is a numerical technique to solve ordinary differential equations of the form
\begin{equation}\label{1}
\frac{dy}{dx}=F(x,y), \ y(x_0)=y_0
\end{equation}
The basic idea is as follows. By the definition of a derivative,
\[y'(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}\]
For small $h>0$, it implies that a reasonable difference quotient approximation for $y'(x)$ is
\begin{equation}\label{2} 
y'(x)=\frac{f(x+h)-f(x)}{h}
\end{equation}
Substitution of (2) into (1) yields the difference equation
\begin{equation}\label{3} 
\frac{f(x+h)-f(x)}{h}=F(x,y)
\end{equation}
However, (3) can be rewritten as
\[f(x+h)=f(x)+h\cdot F(x,y)\]
or equivalently
\begin{equation}\label{4} 
y(x+h)=y(x)+h\cdot F(x,y(x))
\end{equation}
which enables one to approximate $y(x+h)$ in terms of $y(x)$ and $F(x,y(x))$.
Suppose we know the initial value of $x_0$ and $y_0=y(x_0)$. Then set $x_1=x_0+h$ and compute $y_1=y(x_1)=y(x_0+h)=y(x_0)+h\cdot F(x_0, y_0)$. Repeat this process, hence we have a bunch of equations
\[y_1=y_0+h\cdot F(x_0, y_0)\]
\[y_2=y_1+h\cdot F(x_1, y_1)\]
\[y_3=y_2+h\cdot F(x_2, y_2)\]
and so on.
Based on the above equations, the recursive formula can be written as
\[y_{i+1}=y_i+h\cdot F(x_i,y_i)\]
The key point is to choose a sufficient small $h$ since the error of Euler's method is the Taylor series except the first two terms.

R Code

There are 5 parameters in this function. $f$ is the function $F(x, y)$. $h$ is the step. $x0$ and $y0$ are initial values satisfied $y(x_0)=y_0$. $xfinal$ is the final value of $x$. This function will return a data frame which contains each value of $x$ and $y$ at every step. 

Download this post (including examples) as PDF format

没有评论:

发表评论