0% found this document useful (0 votes)
13 views8 pages

R Programs-NS

Uploaded by

aliaisbest271
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

R Programs-NS

Uploaded by

aliaisbest271
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

One Step Euler’s Method

Consider the first order ordinary differential equation


𝑑𝑦
= 𝑓(𝑥, 𝑦)
𝑑𝑥
with initial condition y(x0)= y0
Let xn=x0+nh=xn-1+h, where h is the step size and n is the number of steps.
Formula:
y(xn+1) = yn+1 = yn+h* f(xn,yn)

# Euler's method function


euler=function(f,xn,yn,h,N,n=0){
df=NULL
An=f(xn,yn)
while(n<N){
df=rbind(df,data.frame(n=n,Xn=xn,Yn=yn,An=An,hAn=h*An)) # Combine
into a data frame for tabular output
An=f(xn,yn)
xn=xn+h
yn=yn+h*An
n=n+1
}
print(df)
}
# Define the derivative function f(x, y)
f=function(x,y){
y-x
}
# Run Euler's method
df=euler(f,0,2,0.1,5)

#Output

Practice Questions
1.

2.

3.
Runga-Kutta Method of 2nd Order
Consider the first order ordinary differential equation
𝑑𝑦
= 𝑓(𝑥, 𝑦)
𝑑𝑥
with initial condition y(x0)= y0
Let xn=x0+nh=xn-1+h, where h is the step size and n is the number of steps.
Formula:
K1 = hf(xn,yn)
K2 = hf(xn + h,yn + K1)
K=1/2(K1+ K2)
y(xn+1) = yn+1 = yn+K

# RK 2nd order method function


rk2=function(f,xn,yn,h,N,n=0){
df=NULL
K=f(xn,yn)
while(n<N){
df=rbind(df,data.frame(n=n,Xn=xn,Yn=yn,K=K)) # Combine into a data
frame for tabular output
K1=h*f(xn,yn)
K2=h*f(xn+h,yn+K1)
K=(K1+K2)/2
xn=xn+h
yn=yn+K
n=n+1
}
print(df)
}
# Define the derivative function f(x, y)
f=function(x,y){
x+y
}
# Run RK 2nd order method
df=rk2(f,0,1,0.1,3)

#Output
Practice Questions
1.

2.

3.
Runga-Kutta Method of 4th Order
Consider the first order ordinary differential equation
𝑑𝑦
= 𝑓(𝑥, 𝑦)
𝑑𝑥
with initial condition y(x0)= y0
Let xn=x0+nh=xn-1+h, where h is the step size and n is the number of steps.
Formula:
K1 = hf(xn,yn)
K2 = hf(xn + h/2,yn + K1/2)
K3 = hf(xn + h/2,yn + K2/2)
K4 = hf(xn + h,yn + K3)
K=(K1+2K2+2K3+K4)/6
y(xn+1) = yn+1 = yn+K

# RK 4th order method function


rk4=function(f,xn,yn,h,N,n=0){
df=NULL
K=f(xn,yn)
while(n<N){
df=rbind(df,data.frame(n=n,Xn=xn,Yn=yn,K=K)) # Combine into a data
frame for tabular output
K1=h*f(xn,yn)
K2=h*f(xn+h/2,yn+K1/2)
K3= h*f(xn+h/2,yn+K2/2)
K4= h*f(xn+h,yn+K3)
K=(K1+2*K2+2*K3+K4)/6
xn=xn+h
yn=yn+K
n=n+1
}
print(df)
}
# Define the derivative function f(x, y)
f=function(x,y){
x+y*y
}
# Run RK 4th order method
df=rk4(f,0,1,0.2,3)

#Output
Practice Questions
1.

2.

3.

You might also like