Euler's method
 
 
Given an initial value problem in the form
y'(x)=f(x,y),     y(a)=b
 
Euler's method gives an approximation of the solution.
The sequence of approximating points to the initial value problem, with step size h is given by
xn+1=xn+h,
         
yn+1=yn+hf(tn,yn
x0=a

y0=b
 
 
You will find below a program in R that calculates the sequence of the approximating points for the initial value problem 
y'(x)=xy(x),     y(0)=2
 
Define the function f:
f <- function(x,y){z = x*y}
 
Evaluate the sequence of points. The coordinates will be stored in a matrix z:
 
euler<- function(a,b,h,n){
  z = matrix(0,n+1,2)
  colnames(z)<- c("x","y")
  z[1, ]=c(a,b)
  for (i in 1:n){
    z[i+1,1] <- z[i,1]+h
    z[i+1,2] <- z[i,2]+h*f(z[i,1],z[i,2])
    }
 return(z)
 }
 
The 2 previous functions were copied in a file called euler.R, we get the approximating point an R console:
 
> source("euler.R")
> euler(0,2,0.1,10)

x
y
[1, ]
0.0
2.000000
[2, ]
0.1
2.000000
[3, ]
0.2
2.020000
[4, ]
0.3
2.060400
[5, ]
0.4
2.122212
[6, ]
0.5
2.207100
[7, ]
0.6
2.317456
[8, ]
0.7
2.456503
[9, ]
0.8
2.628458
[10, ]
0.9
2.838735
[11, ]
1.0
3.094221
 
>z <- euler(0,2,.1,10)
>plot(z[ ,1],z[ ,2],type="o")
 
 
 
Copyright 2012-2015, Dr. Fanny Dos Reis