C++ Code
C++ Code
// Example1-2 find the value of area under curve y=x/(1+x2) based on the convergence
parameter
#include <iostream>
#include <cmath>
using namespace std;
float rectangle (float a, float b,int n) //function
{
float h, x, area(0); h=(b-a)/(n+1);
x=a;
for (int i=1; i<=n;i++)
{area =area +f(x);
x=x+h; }
return (area * h);
}
float f(float x) //function for finding y
{return (x/(1.0+x*x));} int main()
{
int n0, n;
float a,b,eps, rc, rn;
cout <<"a,b,n0,eps=?\n";
cin>> a>>b>>n0>>eps;
cout <<"a ="<<a<<"b = "<<b<<endl;
cout <<"n0= " << n0 << "eps = "<<eps <<endl; rc=rectangle(a,b,n0);
n=2*n0;
rn=rectangle (a,b,n);
while (fabs(rn-rc)>eps)
{n=n+n;
rc=rn;
rn=rectangle (a,b,n);
cout <<"integral= "<<rn<<"for n=" <<n<<endl; }
return 0;}
a,b,n0,eps=?
0 1 2 0.0001 a =0b = 1 n0= 2 eps = 0.0001
integral= 0.262593 for n=8
integral= 0.302221 for n=16
integral= 0.323777 for n=32
integral= 0.335016 for n=64
integral= 0.340755 for n=128
integral= 0.343654 for n=256
integral= 0.345111 for n=512
integral= 0.345842 for n=1024
integral= 0.346208 for n=2048
integral= 0.34639 for n=4096
integral= 0.34649 for n=8192
Press any key to continue
Nonlinear
1. The Bisection Method
Example 2-1 Solve the equation sin x − x + 0.5 = 0 and accurate to 4 decimal places by the
bisection method.
// Example-12-1 to find the value of function sin (x) - x +0.5 using bisect method
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float f (float x)
{ return sin (x) - x +0.5 ; }//function
int main(){
int kmax;
float a,b,eps;
cout <<"input a,b,eps,kmax\n";
cin>> a>>b>>eps>>kmax; //kmax =max number of iterations cout <<"the result are\n";
cout <<"k a b x f(x)\n";
int k=1;
float x=0.5*(a+b); //next bisection
while((k<=kmax)&&((b-a)>eps))
{
cout<<k<<setprecision(5)<<setw(12)<<x<<setw(15)<<f(x)<<setprecision(5 )
<<setw(12)<<a<<setw(12)<<b<<endl;//print k,x,y,a,b
if (f(x)>0) a=x; //because f(b)<0
else b=x;
x=0.5*(a+b);
k++;}
if(k>kmax)cout <<"no convergence";
return 0; }
2. Newton Raphson method
Find a real root of the equation x3 – x – 1 = 0 using Newton - Raphson method, correct to
four decimal places.
// Example 2-3 to find the value of function cos(x)=x //using Newton raphson method
#include<iostream>
#include<cmath>
using namespace std;
int main()
{double x;
cout<<"Give initial guess"<< endl;
cin>>x;
double err,tol=1e-5,x1;
int k=1,kmax=100;
err=tol+1;
while(err>tol&&k<kmax)
{x1=x-(x-cos(x))/(1+sin(x));
err=fabs(x1-x);
x=x1;
k++;}
if(err<=tol)
cout<<"The root is"<<x<<endl;
else
cout<<"Error, no convergence\n";
return 0; }