Computationallab 2
Computationallab 2
COMPUTATIONAL METHODS
(ICT 256)
BACHELOR OF TECHNOLOGY IN COMPUTER
SCIENCE
PRACTICAL FILE
Code:
#include <bits/stdc++.h>
#define f(x) cos(x) - x * exp(x)
using namespace std;
int main()
{
float x0, x1, x, f0, f1, f, e;
int step = 1;
cout<< setprecision(6)<< fixed;
up:
cout<<"Enter first guess: ";
cin>>x0;
cout<<"Enter second guess: ";
cin>>x1;
cout<<"Enter tolerable error: ";
cin>>e;
f0 = f(x0);
f1 = f(x1);
if( f0 * f1 > 0.0)
{
cout<<"Incorrect Initial Guesses."<< endl;
goto up;
}
/* Implementing Bisection Method */
cout<<"Bisection Method"<< endl;
do
{
x = (x0 + x1)/2;
f = f(x);
cout<<"Iteration-"<< step<<":\t x = "<< setw(10)<< x<<" and f(x) = "<< setw(10)<< f(x)<< endl;
if( f0 * f < 0)
{
x1 = x;
}
else
{
x0 = x;
}
step = step + 1;
}while(fabs(f)>e);
cout<< endl<< "Root is: "<< x << endl;
}
Output
3. Write a program to implement Newton – Raphson method.
Code:
#include <bits/stdc++.h>
#define f(x) 3*x - cos(x) -1
#define g(x) 3 + sin(x)
using namespace std;
int main()
{
float x0, x1, f0, f1, g0, e;
int step = 1, N;
cout<< setprecision(6)<< fixed;
cout<<"Enter initial guess: ";
cin>>x0;
cout<<"Enter tolerable error: ";
cin>>e;
cout<<"Enter maximum iteration: ";
cin>>N;
/* Implementing Newton Raphson Method */
cout<<"Newton Raphson Method"<< endl;
do
{
g0 = g(x0);
f0 = f(x0);
if(g0 == 0.0)
{
cout<<"Mathematical Error.";
exit(0);
}
x1 = x0 - f0/g0;
cout<<"Iteration-"<< step<<":\t x = "<< setw(10)<< x1<<" and f(x) = "<< setw(10)<< f(x1)<< endl;
x0 = x1;
step = step+1;
if(step > N)
{
cout<<"Not Convergent.";
exit(0);
}
f1 = f(x1);
}while(fabs(f1)>e);
cout<< endl<<"Root is: "<< x1;
}
Output
4. Write a program to implement Secant method.
Code:
#include <bits/stdc++.h>
#define f(x) x*x*x - 2*x - 5
using namespace std;
int main()
{
float x0, x1, x2, f0, f1, f2, e;
int step = 1, N;
cout<< setprecision(6)<< fixed;
cout<<"Enter first guess: ";
cin>>x0;
cout<<"Enter second guess: ";
cin>>x1;
cout<<"Enter tolerable error: ";
cin>>e;
cout<<"Enter maximum iteration: ";
cin>>N;
/* Implementing Secant Method */
cout<<"Secant Method"<< endl;
do
{
f0 = f(x0);
f1 = f(x1);
if(f0 == f1)
{
cout<<"Mathematical Error.";
exit(0);
}
x2 = x1 - (x1 - x0) * f1/(f1-f0);
f2 = f(x2);
cout<<"Iteration-"<< step<<":\t x2 = "<< setw(10)<< x2<<" and f(x2) = "<< setw(10)<< f(x2)<< endl;
x0 = x1, f0 = f1,x1 = x2,f1 = f2;
step = step + 1;
if(step > N)
{
cout<<"Not Convergent.";
exit(0);
}
}while(fabs(f2)>e);
cout<< endl<<"Root is: "<< x2;
}
Output