In: Computer Science
Write the c++ program of Bisection Method and False Position Method and newton Raphson method in a one program using switch condition .Like :
cout<<"1.Bisection Method \n 2.False Position Method\n3.Newton Raphson method"<<endl; if press 1 then work Bisection Method code if press 2 then workFalse Position Method if press 3. work Newton Raphson method .so please writhe the code in c++ using switch case.and the equation given down consider the equation in the given.Note: Must showt the all the step of output all the iteration step shown in the program .in program must shown all the step of iteration result like every iteration x1,x2,x3 must be shown in program.
f(x)=3x-cosx-1;
Please in every itaration must be shown the output then finally Got the root
Below is the code in c++:
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
#define EPSILON 0.00001
#define MAX_ITER 20
double fun(double x)
{
return 3*x-cos(x)-1;
}
double der_fun(double x)
{
return 3+sin(x);
}
void bisection(double a, double b)
{
if (fun(a) * fun(b) >= 0)
{
cout << "You have not assumed right a and b\n";
return;
}
long i=0;
double c = a;
while ((b-a) >= EPSILON)
{
c = (a+b)/2;
cout<<"\nIteration "<<++i<<":\n";
cout<<"a = "<<a<<"\tb = "<<b<<"\tc = "<<c;
if (fun(c) == 0.0)
break;
else if (fun(c)*fun(a) < 0)
b = c;
else
a = c;
}
cout << "\n\n\t\tThe value of root is : " << c;
}
void regula_falsi(double a, double b)
{
if (fun(a) * fun(b) >= 0)
{
cout << "\nYou have not assumed right a and b\n";
return;
}
double c = a;
for (int i=0; i < MAX_ITER; i++)
{
c = (a*fun(b) - b*fun(a))/ (fun(b) - fun(a));
cout<<"\nIteration "<<i+1<<":\n";
cout<<"a = "<<a<<"\tb = "<<b<<"\tc = "<<c;
if (fun(c)==0)
break;
else if (fun(c)*fun(a) < 0)
b = c;
else
a = c;
}
cout << "\n\n\t\tThe value of root is : " << c;
}
void newton_raph(double x)
{
double h = fun(x) / der_fun(x);
long i=0;
while (abs(h) >= EPSILON)
{
h = fun(x)/der_fun(x);
x = x - h;
cout<<"\nIteration "<<i++<<":\n";
cout<<"\t new x = "<<x;
}
cout << "\n\n\t\tThe value of the root is : " << x;
}
int main()
{
double a =-200, b = 300;
double x0 = -200;
int num;
cout<<"\n\n<------------------WELCOME---------------------->";
cout<<"\n\nEquation is 3*x - cos(x) - 1 ";
cout<<"\n\n\t\t<-----------------------MENU---------------------------->";
cout<<"\n\n\t\t Enter 1 to find the ROOT of this equation with BISECTION method";
cout<<"\n\n\t\t Enter 2 find the ROOT of this equation with regula_falsi method";
cout<<"\n\n\t\t Enter 3 find the ROOT of this equation with NEWTON RAPHSON method";
cout<<"\n\n\t\tNOW ENTER____:";
cin>>num;
switch(num)
{
case 1:
bisection(a, b);
break;
case 2:
regula_falsi(a, b);
break;
case 3:
newton_raph(x0);
break;
default:
cout<<"\nWrong Choice!!!!!!!!!LOL";
}
return 0;
}
output
DON'T FORGET TO GIVE A LIKE