Numerical Methods
Numerical Methods
Numerical Methods
Programs
Start
Define the iterative equation
Input x0, initial guess
Input the accuracy
Input the max iterations suggested, n
For i =1 to n, increment in steps of 1
a.
b.
c.
d.
x1= f(x0)
Error=|(x1-x0)/x1|
x0 =x1
If (error<=accuracy) output root=x1 and go to step 8
void main()
{ float f(float );
float x0,x1, error, acc;
int i, n;
cin>>x0>>acc>>n;
for(i=0; i<n; i++)
{
x1=f(x0);
error = fabs((x1-x0)/x1);
x0 = x1;
if (error <= acc)
{
cout<< x1;
go to out;
}
}
cout<<root does not converge;
out:
}
float f(float x)
{
float y=pow(x, 5) - 2 * x * x + 3 * x - 1;
return(y);
}
3. K=0
4. x[k+1] = x[k] - f(x[k]) / f1(x[k])
2.
f0 =f(x0)
3.
f1= f(x1)
4.
For (i = 1 to n) in steps of 1 do
5.
x2= (x0*f1-x1*f0)/(f1-f0)
6.
f2= f(x2)
7.
8.
x1=x2
else
{
x1=x2;
f1 = f2;
}
} while (f2>error);
}
s1 = s2 = s3 = s4 = 0;
for(i = 0; i < n; i++)
{
s1 += x[i];
s2 += x[i] * x[i];
s3 += y[i];
s4 += x[i] * y[i];
}
float d = n * s2 - s1 * s1;
float a = (s2 * s3 - s1 * s4) / d;
float b = (n * s4 - s1 * s3) / d;
cout <<"The equation for the
straight line is: " <<a <<"x + "
<<b;
}
5. Fitting a parabola
void main()
{
float x[20], y[20], a[5][5];
int i, n;
float s1, s2, s3, s4, s5, s6, s7;
void guass(float a[5][5]);
cout <<"\nEnter the no. of values.\n";
cin >>n;
for( i = 0; i < n; i++)
{
cout <<"Enter x[" <<i+1 <<"]
and y[" <<i+1 <<"]";
cin >>x[i] >>y[i];
}
s1 = s2 = s3 = s4 = s5 = s6 = s7 = 0;
5. Fitting a parabola
a[0][0] = (float) n;
a[0][1] = s1;
a[0][2] = s3;
a[0][3] = s2;
a[1][0] = s1;
a[1][1] = s3;
a[1][2] = s4;
a[1][3] = s6;
a[2][0] = s3;
a[2][1] = s4;
a[2][2] = s5;
a[2][3] = s7;
guass(a);
}
5. Fitting a parabola
//Back substitution
x[n-1] = a[n - 1][n] / a[n - 1][n-1];
for(k = n - 2; k >= 0; k--)
{
x[k] = a[k][n];
for(j = k + 1;j < n; j++)
x[k] -= a[k][j] * x[j];
x[k] /= a[k][k];
}
cout <<"The equation for the parabola is: " <<x[2] <<"x^2 + " <<x[1] <<"x +
" <<x[0];
return;
}
6. Trapezoidal rule
void main()
{
float a, b, h, x0, xn, xi;
double sum;
int n, i;
double funct(float a);
7. Simpsons rule
void main()
{
float a, b, h, x0, xn, xi;
double sum;
int n, i;
double funct(float a);
xi = a + (i * h);
h = (b - a) / n;
x0 = a;
xn = b;
sum = funct (x0) + funct (xn);
sum = (h / 3) * sum;
cout <<"The integral is: " <<sum;
}
7. Simpsons rule
double funct(float a)
{
double b;
b = exp (-a * a / 2);
return (b);
}
9. Gauss quadrature
void main()
{
double c[10], x[10];
double sum = 0;
int n, i;
double funct(double a);
c[0] = c[1] = 1;
x[0] = -0.57735;
x[1] = 0.57735;
break;
9. Gauss quadrature
case 5
c[2] = 0.56889;
x[0] = -0.90618;
x[1] = -0.53847;
x[2] = 0;
x[3] = 0.53847;
x[4] = 0.90618;
break;
}
}
double funct(double a)
//Transformed function
{
double b;
b = 3.5 / (3.5 * a + 8.5);
return (b);
}
/* initialisation of coeficients */
for(i=0;i<n;i++)
x[i]=0;
/* calculation of coefficients */
do
{
for(i=0;i<n;i++)
{ y[i]=x[i];
x[i]=a[i][n];
for(j=0;j<n;j++)
if(i!=j)
x[i]=x[i]-a[i][j]*x[j];
x[i]=x[i]/a[i][i];
}
}while(check(n,x,y));