Practical 4
Practical 4
PRO4: write R program to find first order derivatives from the given data
Definition :
Numerical differentiation involves the computation of a derivative of a function f (x) from given
values of f (x) . Such formulas are basic to the numerical solution of differential equations.
Case 1 : if x 0=x
( )
dy
dx x =x
0
1
h [
= Δ y 0−
Δ 2 y 0 Δ3 y 0 Δ4 y 0
2
+
3
−
4
+… ]
When the point x (point to be differentiate) is the first point of given data then we use this forward
interpolation method. Where ‘h’ is the height of the given values of x.
Program in R language :
n <- 6
x <- c(1.5, 2, 2.5, 3, 3.5, 4)
y <- c(3.375, 7, 13.625, 24, 38.875, 59)
for (j in 1:(n-1)) {
for (i in 1:(n-j)) {
if (j==1)
A[i, j] <- (y[i+1] - y[i])
else
A[i, j] <- (A[i+1, j-1] - A[i, j-1])
}
}
print(A)
for (j in 2:(n-1)) {
sum <- sum - (-1)^j * (A[1, j]/j)
}
sum <- 1/h * sum
print(sum)
Here,
As same as previous programs we calculate the forward difference table using given x and y vectors.
Sum is the output variable firstly initialized with first value of forward difference that is Δ y 0
Using for loop we iterate through the first row of forward difference table and using some
calculations we calculate all terms of the formula one by one and then add / subtract them to/from
the sum variable.
After that we divide the sum variable by h which is calculated by subtracting any two values of x
Output :
> print(A)
> print(sum)
[1] 4.75
Case 2 : if x n=x
[ ]
2 3 4
( )
dy
dx x n=x
=
1
h
∇ yn+
∇ yn ∇ yn ∇ yn
2
+
3
+
4
+…
When the point x (point to be differentiate) is the last point of given data then we use this backward
interpolation method. Where ‘h’ is the height of the given values of x.
Program in R language :
n <- 7
x <- c(1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6)
y <- c(7.989, 8.403, 8.781, 9.129, 9.451, 9.750, 10.031)
print(A)
no <- 1.6
h <- x[2] - x[1]
Here,
as same as previous programs we have first calculate the backward difference table using given x and
y vectors.
Sum is the output variable firstly initialized with last value of first backward difference that is ∇ y n
Using for loop we iterate through the backward difference table diagonally (bottom left to top right)
and using some calculations we calculate all terms of the formula one by one and then add them to
the sum variable.
After that we divide the sum variable by h which is calculated by subtracting any two values of x
> print(A)