Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

LAB FILE OF

COMPUTATIONAL METHODS

ES-251

Faculty name: Dr. Soumi Ghosh Student name : Yash Jain


Roll No: 0511480312
Semester : 2 3rd
Group: I2

Maharaja Agrasen Institute of Technology, PSP Area,


Sector – 22, Rohini, New Delhi – 11008
Index
Expt. Program Output File Viva Submission Total
No.
Title
(2 marks) (2 marks) (2 marks) (2 marks) (2 marks) (2 marks)

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

Total Marks
obtained out of
100=k

Marks out of
10,L=k/10

Marks out of
40,M=L*4
PROGRAM 1
AIM
Program for finding roots of f(x)=0 by bisection method.

THEORY
The bisection method is used to find the roots of a polynomial equation. It
separates the interval and subdivides the interval in which the root of the
equation lies. The principle behind this method is the intermediate
theorem for continuous functions. It works by narrowing the gap between
the positive and negative intervals until it closes in on the correct answer.
This method narrows the gap by taking the average of the positive and
negative intervals. It is a simple method and it is relatively slow. The
bisection method is also known as interval halving method, root-finding
method, binary search method or dichotomy method.
Let us consider a continuous function “f” which is defined on the closed
interval [a, b], is given with f(a) and f(b) of different signs. Then by
intermediate theorem, there exists a point x belong to (a, b) for which f(x) = 0.
Advantages of Bisection Method:
● Guaranteed convergence. The bracketing approach is known as the
bisection method, and it is always convergent.
● Errors can be managed. Increasing the number of iterations in the
bisection method always results in a more accurate root.
● The bisection method is simple and straightforward to programme on a
computer.
● In the case of several roots, the bisection procedure is quick
Disadvantages of Bisection Method:
● Although the Bisection method's convergence is guaranteed, it is often
slow.
● Choosing a guess that is close to the root may necessitate numerous
iterations to converge.
● Its rate of convergence is linear. It is incapable of determining complex
roots.
● If the guess interval contains discontinuities, it cannot be used.
● It cannot be applied over an interval where the function returns values
of the same sign.

ALGORITHM
Step-1. Start of the program.
Step-2. Input the variable x1, x2 for the task.
Step-3. Check f(x1)*f(x2)<0
Step-4.If yes proceed
Step-5.If no exit and print error message
Step-6.Repeat 7-11 if condition not satisfied
Step-7. x0=(x1+x2)/2
Step-8. If f(x0)*f(x1)<0
Step-9. x2=x0
Step- . Else
10 . x1=x0
Step- . Condition:
11 . if | (x1-x2)/x1) | < maximum possible error or f(x0)=0
Step- . Print output
12 . End of program.
Step-
13
Step-
14
Step-
15
CODE:
#include <math.h>
#include <stdio.h>

double f(double x) { return x * x - 30; }

double bisection(double x1, double x2, double tol) {


double mid = (x1 + x2) / 2;
double f_mid = f(mid);

printf("%lf\t", mid);

if (fabs(f_mid) <tol) {
return mid;
}

if (f(x1) * f_mid< 0) {
return bisection(x1, mid, tol);
} else {
return bisection(mid, x2, tol);
}
}
int main() {
double x1, x2;
printf("enter first assumption x1: ");
scanf("%lf", &x1);
printf("enter first assumption x2: ");
scanf("%lf", &x2);
double tol = 1e-8; // tolerance for the root

double root = bisection(x1, x2, tol);

printf("\n\nApproximate root: %lf\n", root);

printf("\n#program by Yash");
return 0;
}
OUTPUT

RESULT
Hence, we found roots of f(x)=0 with the help of bisection method.

GRAPH
Equation: x^2-30 =0
PROGRAM 2
AIM:
To find the roots of f(x)=0 using secant method.

THEORY:
Secant method is also a recursive method for finding the root for the
polynomials by successive approximation. It’s similar to the Regular-falsi
method but here we don’t need to check f(x1)f(x2)<0 again and again
after every approximation. In this method, the neighbourhoods roots are
approximated by secant line or chord to the function f(x). It’s also
advantageous of this method that we don’t need to differentiate the given
function f(x), as we do in Newton raphson method.

Advantages of Secant Method:


● The speed of convergence of secant method is faster than that of
Bisection and Regula falsi method.
● It uses the two most recent approximations of root to find new
approximations, instead of using only those approximations which
bound the interval to enclose roo..

Disadvantages of Secant Method:


● The Convergence in secant method is not always assured.
● If at any stage of iteration this method fails.
● Since convergence is not guaranteed, therefore we should put
limit
on maximum number of iterations while implementing this method
on computer.
ALGORITHM:
STEP 1. Decide two initial points x1 and x2 and required accuracy level E.
Compute
STEP 2. f1 = f (x1) and f2 = f (x2)
STEP 3. Compute x3 = (f2 x1 – f1 x2) / (f2 – f1)
If |(x3-
STEP 4.x2)/ x3| > E, then
set x1 = x2 and f1 = f2
set x2 = x3 and f2 = f(x3)
go to step 3
Else
set root = x3
print results
STEP 5. Stop.
CODE:
#include<stdio.h>
#include<math.h>

double f(double x) {
return x*x*x - x -1;
}
double secant(double x1, double x2, double tol) {
double x3 = x2 - f(x2) * ((x2 - x1)/(f(x2) - f(x1)));
printf("%lf\n", x3);
if(fabs(f(x3)) <tol) {
return x3;
} else {
return secant(x2, x3, tol);
}
}

int main() {
double x1, x2;
printf("enter first assumption x1: ");
scanf("%lf", &x1);
printf("enter first assumption x2: ");
scanf("%lf", &x2);

double tol = 1e-6;


double root = secant(x1, x2, tol);
printf("\nApproximate root: %lf\n", root);
printf("program by Yash");
return 0;
}
OUTPUT:

RESULT:
We found roots of f(x)=0 using secant method.
GRAPH:
PROGRAM 3
AIM:
Program for finding roots of f(x)=0 by Newton Raphson Method.

THEORY:
Newton Raphson Method or Newton Method is a powerful technique for
solving equations numerically. It is most commonly used for
approximation of the roots of the real-valued functions. Newton Rapson
Method was developed by Isaac Newton and Joseph Raphson, hence the
name Newton Rapson Method.
Newton Raphson Method involves iteratively refining an initial guess to
converge it toward the desired root. However, the method is not
efficient to calculate the roots of the polynomials or equations with
higher degrees but in the case of small-degree equations, this method
yields very quick results.
In the general form, the Newton-Raphson method formula is written as
follows:
xn = xn-1 – f(xn-1)/f'(xn-1)

Where,
● xn-1 is the estimated (n-1)th root of the function,
● f(xn-1) is the value of the equation at (n-1)th estimated root, and
● f'(xn-1) is the value of the first order derivative of the equation or
function at xn-1.

ALGORITHM:
ST EP-. Start
1 ST. Define function as f(x)
EP- 2. Define first derivative of f(x) as g(x)
ST EP-. Input initial guess (x0), tolerable error (e) and maximum iteration (N)
3 ST. Initialize iteration counter i = 1
EP- 4
ST EP-
5
STEP-6. If g(x0) = 0 then print "Mathematical Error" and goto (12) otherwise
goto (7)
STEP-7. Calculate x1 = x0 - f(x0) / g(x0)
STEP-8. Increment iteration counter i = i + 1
STEP-9. If i>= N then print "Not Convergent" and goto (12) otherwise goto (10)
STEP-10. If |f(x1)| > e then set x0 = x1 and goto (6) otherwise goto (11) STEP-
11. Print root as x1
STEP-12. Stop
CODE:
#include <math.h>
#include <stdio.h>

// Function for which we want to find the root


double f(double x) {
return x * x - 4;
// Change this function to the one you want to find the root for
}

// Derivative of the function


doubledf(double x) {
return 2 * x;
// Change this function to the derivative of your function
}

int main() {
double x0, x1, e;
intmaxIterations;

// Initial guess, tolerance, and maximum number of iterations


printf("Enter initial guess: ");
scanf("%lf", &x0);
printf("Enter tolerance: ");
scanf("%lf", &e);
printf("Enter maximum number of iterations: ");
scanf(" %d", &maxIterations);

// Newton-Raphson method
int iteration = 0;
printf("\niterations\tx0\t\tf(x0)\t\tx1\t\tf(x1)\n");
do {
x1 = x0 - f(x0) / df(x0);

if (fabs(x1 - x0) < e) {


printf("\nRoot found at x = %lf\n", x1);
break;
}
printf(" %d\t%lf\t%lf\t%lf\t%lf\n", iteration, x0, f(x0), x1, f(x1));
x0 = x1;
iteration++;

} while (iteration <maxIterations);

if (iteration >= maxIterations) {


printf("Non convergent within maximum iteration.\n");
}

return 0;
}
OUTPUT:

RESULT:
Hence, we found roots of f(x)=0 with the help of Newton raphson
method.
GRAPH:
PROGRAM 4
AIM: To Implement Lagrange’s Interpolation formula.
THEORY:
Interpolation is a method of finding new data points within the range of a
discrete set of known data points In other words interpolation is the
technique to estimate the value of a mathematical function, for any
intermediate value of the independent variable.
we can apply the Lagrange’s interpolation formula to get our solution.
The Lagrange’s Interpolation formula:
If, y = f(x) takes the values y0, y1, … ,yn corresponding to x = x0, x1 , … ,

xn
then,

This method is preferred over its counterparts like Newton’s method


because it is applicable even for unequally spaced values of x.
We can use interpolation techniques to find an intermediate data point .
Advantages of Lagrange Interpolation:
● This formula is used to find the value of the function even when the
arguments are not equally spaced.
● This formula is used to find the value of independent variable x
corresponding to a given value of a function.
Disadvantages of Lagrange Interpolation:
● A change of degree in Lagrangian polynomial involves a completely
new computation of all the terms.
● For a polynomial of high degree, the formula involves a large
number of multiplications which make the process quite slow.
● In the Lagrange Interpolation, the degree of polynomial is chosen at
the outset. So it is difficult to find the degree of approximating
polynomial which is suitable for given set of tabulated points.

ALGORITHM:
STEP-1. Start
STEP-2. Read number of data (n)
STEP-3 Read data Xi and Yi for i=1 to n
STEP-4. Read value of independent variables say xp whose corresponding
value of dependent say yp is to be determined.
STEP-5. Initialize: yp = 0
STEP-6. For i = 1 to n
Set p = 1
For j =1 to n
If i ≠ j then
Calculate p = p * (xp - Xj)/(Xi - Xj)
End If
Next j
Calculate yp = yp + p * Yi
Next i
STEP-7. Display value of yp as interpolated value
STEP-8. Stop.
CODE:
#include<stdio.h>
void main()
{
printf("\ncode written by yash\n");
float x[100], y[100], xp, yp=0, p;
int i,j,n;
printf("Enter number of data: ");
scanf("%d", &n);
printf("Enter data:\n");
for(i=1;i<=n;i++){
printf("x[%d] = ", i);
scanf("%f", &x[i]);
printf("y[%d] = ", i);
scanf("%f", &y[i]);}
printf("Enter interpolation point: ");
scanf("%f", &xp);
for(i=1;i<=n;i++){
p=1;
for(j=1;j<=n;j++) {
if(i!=j){
p = p* (xp - x[j])/(x[i] - x[j]);}
}
yp = yp + p * y[i];
}
printf("Interpolated value at %.3f is %.3f.", xp, yp);
}

OUTPUT:

RESULT:

Hence, we found the value of y(i) at x(i) i.e interpolation point using
Lagrange Interpolation Formulae.
PROGRAM 5

AIM: To implement newton’s divided difference

method THEORY
Newton’s Divided Difference Formula eliminates the drawback of
recalculation and recomputation of interpolation coe cients by using
Newton’s general interpolation formula which uses “divided differences”.
Before going through the source code for Newton Divided Difference in C,
here’s a brief explanation of what divided differences are with the formula
for divided differences.

ALGORITHM

Step-1. Input:
x: an array of distinct x-values (data points).
y: an array of corresponding y-values (function values).
n: the number of data points (size of arrays).
Step-2. Initialize: Create an array f of size n, where f[i] will represent the
divided difference coefficients.
Step-3. Forward Divided Difference:
For i in the range n, set f[i] equal to y[i].
Step-4. Compute Divided Difference Coefficients:
For i from 1 to n-1, do the following:
For j from n-1 to i, update f[j]
Step-5. Interpolation:
To interpolate a value at a point x0, calculate the result result as
follows: Initialize result to f[0].
For i from 1 to n-1
Step-6. Output:
result will be the interpolated value at x0.
CODE
#include<stdio.h>
void main()
{
printf("Yash jain\n");
printf("Roll no.05114803122");
int x[10], y[10], p[10];
int k,f,n,i,j=1,f1=1,f2=0;
printf("\nEnter the number of observations:\n");
scanf("%d", &n);

printf("\nEnter the different values of x:\n");


for (i=1;i<=n;i++)
scanf("%d", &x[i]);

printf("\nThe corresponding values of y are:\n");


for (i=1;i<=n;i++)
scanf("%d", &y[i]);

f=y[1];
printf("\nEnter the value of 'k' in f(k) you want to evaluate:\n");
scanf("%d", &k);

do
{
for (i=1;i<=n-1;i++)
{
p[i] = ((y[i+1]-y[i])/(x[i+j]-x[i]));
y[i]=p[i];
}
f1=1;
for(i=1;i<=j;i++)
{
f1*=(k-x[i]);
}
f2+=(y[1]*f1);
n--;
j++;
}
while(n!=1);
f+=f2;
printf("\nf(%d) = %d", k , f);
}
OUTPUT

RESULT
● Hence, for f(7) the answer is 10 using newtons divided difference method
PROGRAM 6

AIM: To solve numerical integration by Trapezoidal Rule.


THEORY
In numerical analysis, Trapezoidal method is a technique for evaluating
definite integral. This method is also known as Trapezoidal rule or Trapezium
rule.This method is based on Newton's Cote Quadrature Formula and
Trapezoidal rule is obtained when we put value of n = 1 in this formula.
ALGORITHM
Step-1. Start of the program.
Step-2. Define function f(x)
Step-3. Read lower limit of integration, upper limit of integration
and number of sub interval
Step-4. Calculate: step size = (upper limit- lower
limit)/number of sub interval
Step-5. Set: integration value = f(lower limit) +
f(upper limit)
Step-6. Set: i = 1
Step-7. If i > number of sub interval then goto
Step-8. Calculate: k = lower limit + i * h
Step-9 Calculate: Integration value = Integration
Value + 2* f(k)
Step-10. Increment i by 1 i.e. i=i+1 and go to step 7
Step-11. Calculate: Integration value = Integration
value* step size/2
Step-12. Display Integration value as required
answer
Step-13.Stop.
CODE
#include<stdio.h>
#include<math.h>

/* Define function here */


#define f(x) 1/(1+pow(x,2))

int main()
{
printf("Yash Jain\n");
printf("Roll no.05114803122\n");

float lower, upper, integration=0.0, stepSize, k;


int i, subInterval;
/* Input */
printf("Enter lower limit of integration: ");
scanf("%f", &lower);
printf("Enter upper limit of integration: ");
scanf("%f", &upper);
printf("Enter number of sub intervals: ");
scanf("%d", &subInterval);

/* Calculation */
/* Finding step size */
stepSize = (upper - lower)/subInterval;

/* Finding Integration Value */


integration = f(lower) + f(upper);
for(i=1; i<= subInterval-1; i++)
{
k = lower + i*stepSize;
integration = integration + 2 * f(k);
}
integration = integration * stepSize/2;
printf("\nRequired value of integration is: %.3f", integration);
return 0;
}
OUTPUT

RESULT
● Hence Result is 0.784
PROGRAM 7

AIM: Program for solving numerical integration by simpson’s 1/3 rule

THEORY
It is also known as Simpson's Rule where the rule says:

where f(x) is the integrand, a is the lower limit, and b is the upper limit of integration in
the expression.

ALGORITHM
Step-1. Start of the program.
Step-2. Define Function f(x)
Step-3. Input lower limit, upper limit, sub_interval
Step-4. Calculate: step_size = (lower_limit-upper limit)/sub_interval
Step-5. Calculate: integration f(lower limit) += f(lower_limit) f(upper limit)
Step-6. Set: i=1

Step-7. Loop k= lower_limit + i * step_size


Ifimod2=0
integration integration + 2* f(k)
Else
integration integration + 4 f(k)
End If
i=i+1
While i<= sub_interval
Step-8. integration integration step_size/3
Step-9. Print intgertaion as result
Step-10.Stop.
CODE
#include<stdio.h>
#include<math.h>
#define f(x) 1/(1+x*x)

int main()
{
printf("Yash jain\n");
printf("Roll no.05114803122\n");
float lower, upper, integration=0.0, stepSize,
k; int i, subInterval;

printf("Enter lower limit of integration: ");


scanf("%f", &lower);
printf("Enter upper limit of integration: ");
scanf("%f", &upper);
printf("Enter number of sub intervals: ");
scanf("%d", &subInterval);

stepSize = (upper - lower)/subInterval;

integration = f(lower) + f(upper);


for(i=1; i<= subInterval-1; i++)
{
k = lower + i*stepSize;
if(i%2==0)
{
integration = integration + 2 * f(k);
}
else
{
integration = integration + 4 * f(k);
}
}
integration = integration * stepSize/3;
printf("\nRequired value of integration is: %.3f", integration);
return 0;
OUTPUT

RESULT
● Hence required value of integration is 0.785

You might also like