You are on page 1of 33

Sample Programs -1

1.To fit a straight line through a given set of data points


data fil
e- fit.data
2. Interpolation of evenly spaced data
3. Newton's divided difference interpolation____________________________________
______data file-data.dat
4.Cubic Spline interpolation____________________________________________________
______data file- data.dat
cubic.da
t
5. Interpolation using the Lagrange scheme
6. A two parameter nonlinear fit using chisquare minimization___________________
______data file-non-linear.data
7.To fit a function of the form f(x)=a*g(x) + b*h(x) through the given set of da
ta____data file- gen-linear.data
Sample Programs -2
1.To find the zero of f(x) using false position method.
2.Find the zero of the function f(x) using the secant method
3.Newton-Raphson method to find the zero of the function f(x)
4.Newton-Raphson method to find the zero of the function f(x) when the zero is o
f higher order.
5.To find the zero of a function f(x) by the mid point rule.
6.Use false position method to find the zero of the function f(x) when f(x)= 0 c
an be written as x=g(x)
7.Bairstows method to find the roots of a polynomial____________________________
______Data file- coeff.data
Sample Program
1. Solution of
2. To find the
3. Solution of
4. Solution of

- 3
a set of linear equations by elimination method.
inverse of a matrix using LU decomposition.
a set of linear equations by pivoted elimination method
a set of linear equation by LU decomposition.

Sample Programs - 4
1.To compute the integral of a function using Gauss quadrature method.
2. Interpolation by Newton's divided difference formula_________________________
______Datafile- data.dat
3. Find the solution of a system of non-linear equations
4. To compute the integral of a function using Simpsons rule
5. To compute the integral of a function using mid point rule
********************************************************************************
***************************************
Sample Programs -1
********************************************************************************
***************************************
1.To fit a straight line through a given set of data points_____________________
______data file- fit.data
--------------------------------------------------------------------------------------------------------1.000000 4.100000
1.5200000 7.840000
2.100000 9.000000
2.300000 11.00000
3.200000 12.400000

3.500000 13.900000
4.200000 15.700000
4.500000 16.000000
5.560000 18.500000
5.700000 18.900000
6.000000 20.299999
6.220000 21.000001
7.000000 24.060000
7.527000 22.576000
8.130000 26.372000
8.645000 29.599999
9.210000 29.26001
9.500000 32.800000
10.000000 31.000000
/* To fit a straight line through a given set of data points */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable Declarations and Initialization */
int i,j,n;
float x1,*x,*y,df,df1,xl,a,b,y1;
float S=0.0,Sx=0.0,Sy=0.0,Sxx=0.0,
Syy=0.0,Sxy=0.0,D,chisq;
FILE *FP,*fp1;
n=125;
/* Allocation of memory */
x=(float*) malloc(n);
y=(float*) malloc(n);
/* Reading the data to be modelled */
fp1=fopen("fit.data","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f" "%f",&x1,&y1); x[i]=x1;y[i]=y1;
printf("%d %f\n",i,x[i]);
i++;}
fclose(fp1);
n=i-2;
/* Calculating the coefficients "a" and "b" of the function f(x)=ax+b */
for(i=0;i<=n;i++)
{ S=S+1; Sx=Sx+x[i];Sy=Sy+y[i];Sxx=Sxx+x[i]*x[i];
Syy=Syy+y[i]*y[i]; Sxy=Sxy+x[i]*y[i];
}
D=S*Sxx-Sx*Sx;
a=(S*Sxy-Sx*Sy)/D;
b=-(Sx*Sxy-Sxx*Sy)/D;
/* Print the coeff. on the screen */
printf("%f %f\n",a,b);
/* Calculate the "error" or the fitness of the function */
chisq=0.0;
for(i=0;i<=n;i++)
{

chisq=chisq+(a*x[i]+b-y[i])*(a*x[i]+b-y[i]);
}
printf("
%d xhisq = %f Standard error = %f\n",n-1,chisq, sqrt(chi
sq/(n-1)));
printf("

sigma_a = %f sigma_b = %f\n",S/D,Sxx/D);

}
2. Interpolation of evenly spaced data
--------------------------------------/* Interpolation of evenly spaced data */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Declaration of the variables */
int i,j,n;
float x1,x[15],f[15],y,df,df1,h,s;
FILE *FP;
/* Here we create a data to be interpolated. this part can be
replaced with an "fscanf" while reading from a file */
h=0.5;
i=0;
for(x1=1.0;x1<=3.0;x1=x1+h)
{ x[i]=x1;
f[i]=log10(x1);
printf("%d %f %f\n",i,x[i],f[i]);
i=i+1;
}
n=i-1;
/* Create the divided difference table */
for(j=0;j<n;j++)
{
df=f[j];
for(i=1;i<=(n-j);i++)
{
df1=df;
df=f[i+j]-f[i+j-1];
if(i>1)f[i+j-1]=df1;
}
f[n]=df;
printf("%d %f \n",j, f[j+1]);
}
/* Interpolate using the Newton-Gregory formula */
FP=fopen ("equal.dat","w");
for(x1=1.0;x1<=3.;x1=x1+.2)
{ s=(x1-x[0])/h;
y=(s-(n-1))*f[n]/n;
for(j=n-2;j>=0;j--)
{
y=(s-j)*(y+f[j+1])/(j+1);
}
y=f[0]+y;

fprintf(FP,"%f %f \n",x1, y);}


fclose(FP);
}
3. Newton's divided difference interpolation____________________________________
___data file-data.dat
---------------------------------------------------------------------------------------------------0.60000002 0.518823624
0.75000002 0.718823624
1.05928254 0.637418389
1.11524534 0.310572922
1.49329114 0.634586275
1.84503245 0.195216343
2.14226007 0.358885348
2.39050388 -0.136540428
2.72717857 -0.0872502401
2.80259895 -0.00997328665
/* Newtion's divided difference interpolation /*
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Declaration of variables */
int i,j,n;
float x1,x[15],f[15],y,df,df1,dx;
FILE *FP;
/* Open the data file to be interpolated */
FP=fopen ("data.dat","r");
/* Read the data till the end of the file */
i=0;
while(!feof(FP))
{fscanf(FP,"%f %f \n",&x[i],&f[i]); i++;}
fclose(FP);
n=i-1;
/* construct the divided difference table */
for(j=0;j<n;j++)
{
df=f[j];
for(i=1;i<=(n-j);i++)
{
df1=df;
df=(f[i+j]-f[i+j-1])/(x[i+j]-x[i-1]);
if(i>1)f[i+j-1]=df1;
}
/* Store the coefficients of the polynomials in the f[i] array */
f[n]=df;
printf("%d %f \n",j, f[j+1]);
}

/* Interpolate between the first four points */


FP=fopen ("newton.dat","w");
dx=(x[3]-x[0])/15.0;
for(x1=x[0];x1<=x[3];x1=x1+dx)
{ y=f[0]+(x1-x[0])*(f[1]+(x1-x[1])
*(f[2]+(x1-x[2])*f[3]));
fprintf(FP,"%f %f \n",x1, y);}
fclose(FP);
}
4.Cubic Spline interpolation___________data file- data.dat
---------------------------------------------------------data.dat
0.60000002 0.518823624
0.75000002 0.718823624
1.05928254 0.637418389
1.11524534 0.310572922
1.49329114 0.634586275
1.84503245 0.195216343
2.14226007 0.358885348
2.39050388 -0.136540428
2.72717857 -0.0872502401
2.80259895 -0.00997328665
cubic.dat
0.700000 0.666641
0.730000 0.700592
0.850000 0.970026
0.911857 1.021665
0.973713 0.960349
1.035570 0.758162
1.215245 -0.059315
1.290855 -0.031059
1.366464 0.165791
1.442073 0.444050
1.593291 0.523870
1.663639 0.414649
1.733988 0.306483
1.804336 0.222987
1.945032 0.267931
2.004478 0.326193
2.063924 0.367807
2.123369 0.370075
2.242260 0.177605
2.291909 0.060416
2.341558 -0.050645
2.490504 -0.243457
2.557839 -0.242801
2.625174 -0.200160
2.692508 -0.129721
/* Cubic Spline interpolation */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable declarations */

int i,j,n;
float x1,x[16],f[16],e[16],d[16],h[16],r[16],z[16],y,df,dx,xs;
FILE *FP,*fp1;
/* Read the file to be interpolated */
fp1=fopen("data.dat","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f" "%f",&x[i],&f[i]);
i++;}
fclose(fp1);
n=i-1;
printf("%d\n",n);
/* Calculating the coefficients of the polynomial for
every interval */
for(i=0;i<=n-2;i++)
{
e[i]=2.0*(x[i+2]-x[i]);
}
for(i=0;i<=n-2;i++)
{
h[i]=x[i+2]-x[i+1];
}
for(i=0;i<=n-1;i++)
{
d[i]=x[i+1]-x[i];
}
for(i=0;i<=n-2;i++)
{
r[i]=6*(f[i+2]-f[i+1])/h[i]-6*(f[i+1]-f[i])/d[i];
printf("%f %f %f %f \n",e[i],d[i],h[i],r[i]);
}
for(i=0;i<=n-3;i++)
{
df=d[i]/e[i];
e[i+1]=e[i+1]-df*h[i];
r[i+1]=r[i+1]-df*r[i];
}
for(i=n-3;i<=0;i--)
{
df=h[i]/e[i+1];
r[i+1]=r[i]-r[i+1]*df;
}
for(i=0;i<=n-2;i++)
{
z[i+1]=r[i]/e[i];
}
z[0]=0;
z[n]=0;
/* Interpolating, using a different polynomial for each interval */
FP=fopen ("cubic.dat","w");
for(i=0;i<n;i++)
{
dx=(x[i+1]-x[i])/5.0;
xs=x[i]+.1;
for(x1=xs;x1<x[i+1];x1=x1+dx)
{
y=-z[i]*pow((x1-x[i+1]),3)/(6.0*d[i])+
z[i+1]*pow((x1-x[i]),3)/(6.0*d[i])+
(f[i+1]/d[i]-z[i+1]*d[i]/6.0)*(x1-x[i])+

(-f[i]/d[i]+z[i]*d[i]/6.0)*(x1-x[i+1]);
fprintf(FP,"%f %f \n",x1, y);}
}
fclose(FP);
}
5. Interpolation using the Lagrange scheme
-----------------------------------------/* Interpolation using the Lagrange scheme */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable declarations */
int i,j,n;
float x1,x[15],f[15],y,df,df1,xl;
FILE *FP,*fp1;
/* Read the file to be interpolated */
fp1=fopen("tointer.data","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f" "%f",&x[i],&f[i]);
i++;}
fclose(fp1);
n=i-2;
/* Interpolation using the nested Lagrange form */
for(i=0;i<=n;i++)
printf("%d %f %f\n",i,x[i],f[i]);
xl=x[n];
FP=fopen ("lagrange.dat","w");
for(x1=x[0];x1<=x[n];x1=x1+.1)
{
y=0.0;
for(i=0;i<=n;i++)
{ df=1.0;
for(j=0;j<=n;j++)
{
if(j!=i)
{
df=df*(x1-x[j])/(x[i]-x[j]);
}
}
y=y+df*f[i];
}
fprintf(FP,"%f %f \n",x1, y);
}
fclose(FP);
}
6. A two parameter nonlinear fit using chisquare minimization_______________data
file-non-linear.data

----------------------------------------------------------------------------------------------------0.000000 4.348900
0.200000 2.854599
0.400000 2.572584
0.600000 1.938492
0.800000 1.326875
1.000000 1.018719
1.200000 0.978789
1.400000 0.753649
1.600000 0.500191
1.800000 0.368544
2.000000 0.301258
2.200000 0.302694
2.400000 0.208578
2.600000 0.195656
2.800000 0.121445
/* A two parameter nonlinear fit using chisquare minimization */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable declarations and initializations */
int i,j,n;
float x[25],y[25],D[2][2],d[2],a1,a2;
float S=0.0,Sx=0.0,Sy=0.0,Sxx=0.0,
Syy=0.0,Sxy=0.0,DD,L;
float chisq,chisq_old;
FILE *FP,*fp1;
/* Read the data to be fitted with */
fp1=fopen("non-linear.data","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f" "%f",&x[i],&y[i]);
i++;
}
fclose(fp1);
n=i-2;
/* read the initial guesses for the parameters from the screen */
scanf("%f" "%f",&a1,&a2);
/* Calculate the chisquare with the guess value */
chisq=0.0;
for(i=0;i<=n;i++)
{
chisq=chisq+(exp(a1*x[i])+
3.0*exp(a2*x[i])-y[i])*(exp(a1*x[i])+
3.0*exp(a2*x[i])-y[i]);
}
/* d[2] contains the first derivative of chisquare with respect to the
paramters, summed over all points */
d[0]=1.0; d[1]=1.0; L=1.0;
/* Iterate for the parameters till the first derivatives of chisquare are small
*/
while(fabs(d[0])+fabs(d[1])>0.01)

{
/* D[2][2] contains the second derivatives of chisquare w.r.t the parameters, an
d
summed over all points */
D[0][0]=0.0;
D[0][1]=0.0;
D[1][0]=0.0;
D[1][1]=0.0;
d[0]=0.0;
d[1]=0.0;
/* the diagonal elements of the D[2][2] are weighted by (1+L) */
for(i=0;i<=n;i++)
{ D[0][0]=D[0][0]+2*x[i]*x[i]*
exp(2*a1*x[i])*(1.0+L);
D[0][1]=D[0][1]+6*x[i]*x[i]*
exp(a1*x[i])*exp(a2*x[i]);
D[1][0]=D[1][0]+6*x[i]*x[i]*
exp(a1*x[i])*exp(a2*x[i]);
D[1][1]=D[1][1]+2*x[i]*x[i]*9
*exp(2*a2*x[i])*(1.0+L);
d[0]=d[0]-(y[i]-(exp(a1*x[i])+3.0*exp(a2*x[i])))*x[i]*exp(a1*x[i]);
d[1]=d[1]-(y[i]-(exp(a1*x[i])+3.0*exp(a2*x[i])))*3*x[i]*exp(a2*x[i]);
}
DD=D[1][1]*D[0][0]-D[0][1]*D[1][0];
printf("%f %f %f %f\n",D[0][0],D[1][0],D[0][1],D[1][1]);
printf("%f %f\n",d[0],d[1]);
/* Calculate the new value of paramters */
a1=a1-(D[1][1]*d[0]-D[0][1]*d[1])/DD;
a2=a2-(D[0][0]*d[1]-D[1][0]*d[0])/DD;
printf("n = %d
a1 = %f a2 = %f

L = %f\n",n,a1,a2,L);

/* Store the chisquare value before calculating it again with the new parameters
. */
chisq_old=chisq;
/* Chisquare with the new paramters */
chisq=0.0;
for(i=0;i<=n;i++)
{
chisq=chisq+(exp(a1*x[i])+3.0*exp(a2*x[i])-y[i])*(exp(a1*x[i])+3.0*exp
(a2*x[i])-y[i]);
}
/* If the iteration is not moving in the correct direction increase the weight f
or diagonal
terms of D[2][2] */
if(chisq>=chisq_old)L=L*10.0;
/* decrease the weight if the iteration is progressing well */
if(chisq<chisq_old)L=L*.1;
}
printf("
%d xhisq = %f Standard error = %f\n",n-1,chisq, sqrt(chi
sq/(n-1)));

}
7.To fit a function of the form f(x)=a*g(x) + b*h(x) through the given set of da
ta____data file- gen-linear.data
--------------------------------------------------------------------------------------------------------------0.000000 2.990000
0.200000 2.745795
0.400000 1.347783
0.600000 1.528873
0.800000 1.970880
1.000000 1.060759
1.200000 0.788752
1.400000 0.947361
1.600000 0.530716
1.800000 0.734169
2.000000 0.654004
2.200000 0.287231
2.400000 0.531436
2.600000 0.184658
2.800000 0.305304
/* Fit a function of the form f(x)=a*g(x)+b*h(x) through the given set of data *
/
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Declaration of vairables */
int i,j,n;
float x1,x[25],y[25],df,df1,xl,a,b,al[2][2],be[2];
float S=0.0,Sx=0.0,Sy=0.0,Sxx=0.0,Syy=0.0,Sxy=0.0,D;
float chisq;
FILE *FP,*fp1;
/* Reading the data to be fitted with */
fp1=fopen("gen-linear.data","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f" "%f",&x[i],&y[i]);
i++;
}
fclose(fp1);
n=i-2;
/* Initialize the array to calculate, the sum of, the product of derivatives */
al[0][0]=0.0;
al[0][1]=0.0;
al[1][0]=0.0;
al[1][1]=0.0;
be[0]=0.0;
be[1]=0.0;
/* sum the product of the derivatives over all points */
for(i=0;i<=n;i++)
{ al[0][0]=al[0][0]+exp(-2.0*x[i]);
al[0][1]=al[0][1]+exp(-x[i])/(1.0+x[i]);
al[1][0]=al[1][0]+exp(-x[i])/(1.0+x[i]);

al[1][1]=al[1][1]+1.0/((1.0+x[i])*(1+x[i]));
be[0]=be[0]+y[i]*exp(-x[i]);
be[1]=be[1]+y[i]/(1+x[i]);
}
/* Calculate the determinant of the matrix "a" */
D=al[1][1]*al[0][0]-al[0][1]*al[1][0];
/* Calculate the coefficients "a" and "b".
a=(al[1][1]*be[0]-al[0][1]*be[1])/D;
b=(al[0][0]*be[1]-al[1][0]*be[0])/D;
printf("n = %d
a = %f b = %f\n",n,a,b);
/* Calculate the error in the fit. */
chisq=0.0;
for(i=0;i<=n;i++)
{
chisq=chisq+(a*exp(-x[i])+b/(1+x[i])-y[i])*(a*exp(-x[i])+b/(1+x[i])-y[
i]);
}
printf("
%d xhisq = %f Standard error = %f\n",n-1,chisq, sqrt(chi
sq/(n-1)));

}
********************************************************************************
***************************************
Sample Programs -2
********************************************************************************
***************************************
1.To find the zero of f(x) using false position method.
------------------------------------------------------/* find the zero of f(x) using false-position method. Here one starts with the
a pair of points bracketing the zero. The point of intersection of the
line connecting this points with the x-axis is taken as the solution
in the next iteration */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function that evaluates f(x) */
float func(float);
main()
{
/* Variable declarations */
float s,x0,x1;
float false_position();
FILE *FP,*fp1;
/* the first guesses that bracket the zero. It is
assumed that f(x0) is negative and f(x1) is positive */
scanf("%f" "%f",&x0,&x1);
* Call the function "false-position" to obtain the zero.
Pass the pointer to the function "func" that evaluate the function at any
point. This "func" must be declared global , that is outside the main function *

/
s=false_position(x0,x1,&func);
printf(" The zero is %f\n",s);
}
/* function to find the zero using false-position rule. */
float false_position(x0,x1,function)
/* declaration of the arguments recieved */
float x0,x1;
float function(float);
{
int i,j,n,m;
float e,f;
float x2;
e=1.0;
/* continue till close to the zero */
while(e>0.0001)
{
/* Find the new solution by fiding the point of intersection of the
line connecting (x0,f(x0)) and (x1,f(x1)) with the x-axis. */
x2=x1+function(x1)*(x0-x1)/(function(x1)-function(x0));
if(function(x2)<0)
/* if f(x2) is negative replace x0 with x2 */
{e=fabs((x0-x2)/x2);x0=x2;}
/* if f(x2) is positive replace x1 with x2 */
if(function(x2)>0)
{e=fabs((x1-x2)/x2);x1=x2;}
printf(" %f %f %f\n",e,x2,function(x2));
}
/* return x2 as the zero when the error condition is satisfied */
return x2;
}
/* user supplied routine that evaluates f(x).
Note that the name "func" can be changed without
changing "function" in the
routine that evaluates false-position*/
float func(float x)
{
float y;
y=1.0-x*x+log10(1.0+x);
return y;
}
2.Find the zero of the function f(x) using the secant method
------------------------------------------------------------/* find the zero of the function f(x) using the secant method */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* External function that returns the value of f(x) */
float func(float);
main()
{
/* Variable declarations */
float s,x0,x1;
float sec();

FILE *FP,*fp1;
/* the initial guesses. Unlike the bracketing methods these two
values need not enclose the zero of f(x) */
scanf("%f" "%f",&x0,&x1);
/* call the funcion "sec" that computes the zero using secant method.
Pass the two initial guess values and the pointer to the external function
that evaluates f(x) */
s=sec(x0,x1,&func);
printf(" The zero is %f\n",s);
}
/* the function that compute the zero of f(x) using iterations based on
secant method. it recieves two guess values "x0" and "x1" and the pointer to
the function that computes f(x) */
float sec(x0,x1,function)
float x0,x1;
float function(float);
{
int i,j,n,m;
float e,f;
float x2;
e=1.0;
/* continue the iteration till the error defined as the percentage
change between two iterations is small */
while(e>0.0001)
{
/* the new approxiation is obtained from the the present one as the
point of intersection of the line joining (x0,f(x0)) and (x1,f(x1))
with the x-axis */
x2=(function(x1)*x0-function(x0)*x1)/(function(x1)-function(x0));
e=fabs((x1-x2)/x2);
printf(" %f %f %f\n",e,x2,function(x2));
/* always replace x0 with x1 and x1 with the new point */
x0=x1;
x1=x2;
}
return x2;
}
float func(float x)
{
float y;
y=1.0-x*x+log(1.0+x);
return y;
}
3.Newton-Raphson method to find the zero of the function f(x)
-------------------------------------------------------------/* Newton-Raphson method to find the zero of the function f(x) */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function to evaluate f(x) and its first derivative*/
void func(float,float*,float*);
main()
{

/* Declaration of the variables */


float s,x1;
float newton();
FILE *FP,*fp1;
/* Initial guess for the zero */
scanf("%f",&x1);
/* call the function to find the zero using newton-raphson iteration.
Pass the pointer to the external function that evaluate f(x) and its derivative
*/
s=newton(x1,&func);
printf(" The zero is %f\n",s);
}
/* the function that computes the zero of f(x) using newton-raphson interation
it recieves the external function to evaluate f(x) as "function" and the
current approximation of the zero as "x1" */
float newton(x1,function)
float x1;
/* the "function" is called with two pointers through which the value of f(x)
and its derivatives are updated. Since this function does not "return" any
variables it is of type "void" */
void function(float,float*,float*);
{
int i,j,n,m;
float e,*f,*deriv;
float x2;
e=1.0;
/* continue the iteration till the error defined as the percentage
change between two iterations is small */
while(e>0.0001)
{
/* call the "function" to get the value of f(x) in "f" and its
derivative in "deriv" */
function(x1,f,deriv);
/* the new approxiation is obtained from the Taylor expansion around
the present one */
x2=x1-(*f)/(*deriv);
e=fabs((x1-x2)/x2);
printf(" %f %f %f %f %f\n",e,x2,x1,*f,*deriv);
x1=x2;
}
return x2;
}
/* the external function that recives "x" and evaluates f(x) and its
derivative. since "y" and "deriv" are pointers they are passed by reference.
This means that any change in their value made here will be reflected in the
function from which it is called and no explicit "return" statements are require
d */
void func(float x, float *y, float *deriv)
{
*y=1.0-x*x+log(1.0+x);
*deriv=-2*x+1.0/(1.0+x);
//*y=x-exp(-2.0*x);
//*deriv=1+2.0*exp(-2.0*x);
}
4.Newton-Raphson method to find the zero of the function f(x) when the zero is o

f higher order.
---------------------------------------------------------------------------------------------/* Newton-Raphson method to find the zero of the function f(x) when
the zero is of higher order, that is when the function and its first derivative
are going to zero*/
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function to evaluate f(x) and its first two derivatives
*/
void func(float,float*,float[]);
main()
{
/* Declaration of the variables */
float s,x1;
float newton();
FILE *FP,*fp1;
/* Initial guess for the zero */
scanf("%f",&x1);
/* call the function to find the zero using a higher order newton-raphson iterat
ion.
Pass the pointer to the external function that evaluate f(x) and its derivative
*/
s=newton(x1,&func);
printf(" The zero is %f\n",s);
}
/* the function that computes the zero of f(x) using newton-raphson interation
it recieves the external function to evaluate f(x) and its derivatives as
"function" and the current approximation of the zero as "x1" */
float newton(x1,function)
float x1;
/* the "function" is called with a pointer and an array
through which the value of f(x) and its derivatives are updated.
Since this function does not "return" any variables it is of type "void" */
void function(float,float*,float[]);
{
int i,j,n,m;
float e,*f,deriv[2];
float x2;
e=1.0;
/* continue the iteration till the error defined as the percentage
change between two iterations is small */
while(e>0.000001)
{
/* call the "function" to get the value of f(x) in "f" and its
derivatives in the array"deriv" */
function(x1,f,deriv);
/* the new approxiation is obtained from the Taylor expansion up to second
derivative, around the present one */
x2=x1-(*f)*deriv[0]/( deriv[0]*deriv[0]-(*f)*deriv[1]);
e=fabs((x1-x2)/x2);
printf(" %e %e %e %e %e\n",e,x2,x1,*f,deriv[0]);
x1=x2;
}

return x2;
}
* the external function that recieves "x" and evaluates f(x) and its
derivatives. since "y" is a pointer and "deriv" is an array, they are passed by
reference.
This means that any change in their value made here will be reflected in the
function from which it is called and no explicit "return" statements are require
d */
void func(float x, float *y, float deriv[2])
{
*y=pow(x,4)-6*pow(x,3)+12*pow(x,2)-10*x+3;
deriv[0]=4*pow(x,3)-18*x*x+24*x-10;
printf("%f\n",deriv[0]);
deriv[1]=12*x*x-36*x+24;
printf("%f\n",deriv[1]);
}
5.To find the zero of a function f(x) by the mid point rule.
-----------------------------------------------------------/* to find the zero of a function f(x) by the mid point rule
Also demonstrates the use of pointer to a function */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function that evaluates f(x) */
float func(float);
main()
{
/* Variable declarations */
float s,x0,x1;
float midpoint();
FILE *FP,*fp1;
/* the first guesses that bracket the zero. It is
assumed that the function is negative for x0 and positive for x1 */
scanf("%f" "%f",&x0,&x1);
/* Call the function "midpoint" to obtain the zero using midpoint rule.
Pass the pointer to the function "func" that evaluate the function at any
point. This "func" must be declared global , that is outside the main function *
/
s=midpoint(x0,x1,&func);
printf(" The zero is %f\n",s);
}
/* function to find the zero using midpoint rule. */
float midpoint(x0,x1,function)
/* declaration of the arguments recieved */
float x0,x1;
float function(float);
{
int i,j,n,m;
float e,f;
float x2;
e=1.0;
/* continue till close to the zero */

/*
/*
/*

/*
/

while(e>0.0001)
{
find the midpoint */
x2=(x1+x0)/2.0;
if the finction if negative at midpoint replace x0 with x2 */
if(function(x2)<0)
{e=fabs((x0-x2)/x2);x0=x2;}
if the finction if positive at midpoint replace x1 with x2 */
if(function(x2)>0)
{e=fabs((x1-x2)/x2);x1=x2;}
printf(" %f %f %f\n",e,x2,function(x2));
}
return the midpoint value as the zero when the error condition is satisfied *
return x2;
}

/* user supplied routine that evaluates the function whose zero is to be found
Note that the name "func" can be changed without changin "function" in the
routine that evaluates midpoint */
float func(float x)
{
float y;
y=1.0-x*x+log10(1.0+x);
return y;
}
6.Use false position method to find the zero of the function f(x) when f(x)= 0 c
an be written as x=g(x)
-----------------------------------------------------------------------------------------------------/* False position method to find the zero of the function f(x) when
f(x)=0 can be written as x=g(x) */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function to evaluate g(x) */
float func(float);
main()
{
/* Declaration of the variables */
float s,x1;
float fixedpoint();
FILE *FP,*fp1;
/* Initial guess for the zero */
scanf("%f",&x1);
/* call the function to find the zero using fixed point iteration.
Pass the pointer to the external function that evaluate g(x) */
s=fixedpoint(x1,&func);
printf(" The zero is %f\n",s);
}
/* the function that computes the zero of f(x) using fixed point interation
it recieves the external function to evaluate g(x) as "function" and the
current approximation of the zero as "x1" */
float fixedpoint(x1,function)

float x1;
float function(float);
{
int i,j,n,m;
float e,f;
float x2;
e=1.0;
/* continue the iteration till the error defined as the percentage
change between two iterations is small */
while(e>0.0001)
{
/* use x=g(x) to get the next approximation to the zero */
x2=function(x1);
e=fabs((x1-x2)/x2);
printf(" %f %f %f\n",e,x2,function(x2));
x1=x2;
}
return x2;
}
float func(float x)
{
float y;
y=(1.0+log10(1.0+x))/x;
return y;
}
7.Bairstows method to find the roots of a polynomial__________________Data filecoeff.data
------------------------------------------------------------------------------------------1.25
-3.875
2.125
2.75
-3.5
1.0
/* Bairstows method to find the roots of a polynomial.*/
/*

Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable Declarations */
int i,j,n,m;
float a[25],b[25],D[2][2],d[2],c[25];
float r,s,DD,x;
FILE *FP,*fp1;
/* Read the coefficients of a polynomial from the file "coeff.data" */
fp1=fopen("coeff.data","r");
i=0;
while(!feof(fp1))
{fscanf(fp1,"%f",&a[i]);
i++;

}
fclose(fp1);
/* Order of the polynomial */
n=i-2;
/* Initial guess for the coefficients of the first quadratic factor */
scanf("%f" "%f",&r,&s);

/*

/*
/*
/*

/*

m=n;
for(i=0;i<=m-1;i++)
{
b[1]=1.0; b[0]=1.0;
Iterate till the remainders are zero */
while(fabs(b[1])+fabs(b[0])>0.001)
{
if(m>2)
{b[m]=a[m]; b[m-1]=a[m-1]+r*b[n];
for(j=m-2;j>=0;j--)
{b[j]=a[j]+r*b[j+1]+s*b[j+2];}
}
if(m>2)
{c[m]=b[m]; c[m-1]=b[m-1]+r*c[n];
for(j=m-2;j>=1;j--)
{c[j]=b[j]+r*c[j+1]+s*c[j+2];}
}
printf("%d\n",i);
D[0][0]=c[2];
D[0][1]=c[3];
D[1][0]=c[1];
D[1][1]=c[2];
d[0]=-b[1];
d[1]=-b[0];
DD=D[1][1]*D[0][0]-D[0][1]*D[1][0];
printf("%f\n",DD);
Update the coefficients */
r=r+(D[1][1]*d[0]-D[0][1]*d[1])/DD;
s=s+(D[0][0]*d[1]-D[1][0]*d[0])/DD;
printf("m = %d r = %f s = %f b[0] = %f b[1] = %f \n"
,m,r,s,b[0],b[1]);*/
}
the roots of the quadratic fraction */
x=r*r+4.0*s;
if(x>=0.0)
{
printf("\n");
printf ("Solution x = %f x = %f \n",
(r+sqrt(x))/2, (r-sqrt(x))/2.0);
}
if(x<0.0)
{
printf("\n");
printf ("Solution x = %f + i %f x = %f - i %f \n",
r/2.0,sqrt(-x)/2.0, r/2.0,sqrt(-x)/2.0);
}
the order of the polynomial is reduced by 2 */
m=m-2;
printf("\n");
printf(" The quotient polynomial coeff:\n");
printf("\n");

for(j=0;j<=m;j++)
{ a[j]=b[j+2]; printf ("%d

%f \n", j, a[j]); }

}
/* go back to find the next quadratic fraction with the present
solutions as the initial guess */
}
********************************************************************************
***************************************
Sample Programs -3
********************************************************************************
***************************************
1. Solution of a set of linear equations by elimination method.
--------------------------------------------------------------/* Solution of a set of linear equations by elimination method */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* variable declarations */
int i,j,n,k,m;
float D[3][3],d[3],x,s[3];
FILE *FP,*fp1;
n=2;
/* the equation is [D][s]=[d] */
/* read the matrix [D] and [d] */
D[0][0]=3.0;
D[0][1]=2.0;
D[0][2]=1.1;
D[1][0]=6.0;
D[1][1]=2.0;
D[1][2]=1.;
D[2][0]=1.0;
D[2][1]=4.0;
D[2][2]=2.0;
d[0]=7.65;
d[1]=13.5;
d[2]=16.0;
/* print the matrix elements and the RHS on the screen */
for(j=0;j<=2;j++)
{
printf(" %f %f %f
%f\n",D[j][0],D[j][1],D[j][2],d[j]);
}
/* eliminate column by column */
for(k=0;k<=n;k++)
{
for(j=k+1;j<=n;j++)
{
/* to eliminate the kth column, subtract from all rows j >i k,
the elements of the kth row, divided by its diagonal element and
multuplied by the kth element of the jth row. */

x=D[j][k]/D[k][k];
for(i=k;i<=n;i++)
{
D[j][i]=D[j][i]-x*D[k][i];
}
/* do the same operation on the RHS too */
d[j]=d[j]-d[k]*x;
}
/* print the matrix at the end of each column elimination */
printf("\n");
for(m=0;m<=2;m++)
{
printf(" %f %f %f
%f\n",D[m][0],D[m][1],D[m][2],d[m]);
}
}
/* obtain the solution by back substitution */
printf("The solution\n");
for(i=n;i>=0;i--)
{ x=0.0;
for(j=i+1;j<=n;j++)
{ x=x+D[i][j]*s[j];}
s[i]=(d[i]-x)/D[i][i];
printf(" %d %f \n", i,s[i]);
}
}
2. To find the inverse of a matrix using LU decomposition.
---------------------------------------------------------/* To find the inverse of a matrix using LU decomposition */
/* standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable declarations */
int i,j,n,m,an,am;
float D[3][3],d[3],C[3][3];
float x,s[3][3],y[3];
void LU();
FILE *FP,*fp1;
an=3; am=3;
n=2;
/* the matrix to be inverted */
D[0][0]=3.0;
D[0][1]=2.0;
D[0][2]=1.1;
D[1][0]=6.0;
D[1][1]=2.0;
D[1][2]=1.;
D[2][0]=1.0;
D[2][1]=4.0;
D[2][2]=2.0;
/* Store the matrix value for camparison later.
this is just to check the results, we don't need this

array for the program to work */


for(m=0;m<=2;m++)
{
for(j=0;j<=2;j++)
{
C[m][j]=D[m][j];
}
}
/* Call a sub-function to calculate the LU decomposed matrix. Note that
we pass the two dimensional array [D] to the function and get it back */
LU(D,n);
printf(" \n");
printf("The matrix LU decomposed \n");
for(m=0;m<=2;m++)
{
printf(" %f %f %f \n",D[m][0],D[m][1],D[m][2]);
}
/* TO FIND THE INVERSE */
/* to find the inverse we solve [D][y]=[d] with only one element in
the [d] array put equal to one at a time */
for(m=0;m<=2;m++)
{
d[0]=0.0;d[1]=0.0;d[2]=0.0;
d[m]=1.0;
for(i=0;i<=n;i++)
{ x=0.0;
for(j=0;j<=i-1;j++)
{ x=x+D[i][j]*y[j];}
y[i]=(d[i]-x);
}
for(i=n;i>=0;i--)
{ x=0.0;
for(j=i+1;j<=n;j++)
{ x=x+D[i][j]*s[j][m];}
s[i][m]=(y[i]-x)/D[i][i];
}
}
/* Print the inverse matrix */
printf("The Inverse Matrix\n");
for(m=0;m<=2;m++)
{
printf(" %f %f %f \n", s[m][0],s[m][1],s[m][2]);
}
/* check that the product of the matrix with its iverse results
is indeed a unit matrix */
printf("The product\n");
for(m=0;m<=2;m++)
{
for(j=0;j<=2;j++)
{
x=0.0;
for(i=0;i<=2;i++)
{ x=x+C[m][i]*s[i][j]; }

printf(" %d

%d

%f \n", m,j,x );

}
}
}
/* The function that calcualtes the LU deomposed matrix.
Note that it receives the matrix as a two dimensional array
of pointers. Any change made to [D] here will also change its
value in the main function. So there is no need of an explicit
"return" statement and the function is of type "void". */
LU(float(*D)[3][3],int n)
{
int i,j,k,m,an,am;
float x;
printf("The matrix \n");
for(j=0;j<=2;j++)
{
printf(" %f %f %f \n",(*D)[j][0],(*D)[j][1],(*D)[j][2]);
}
for(k=0;k<=n-1;k++)
{
for(j=k+1;j<=n;j++)
{
x=(*D)[j][k]/(*D)[k][k];
for(i=k;i<=n;i++)
{
(*D)[j][i]=(*D)[j][i]-x*(*D)[k][i];
}
(*D)[j][k]=x;
}
}
}
3. Solution of a set of linear equations by pivoted elimination method
----------------------------------------------------------------------/* Solution of a set of linear equations by pivoted-elimination method */
/* Standard Headers */

/*
/*

/*
/*

#include<math.h>
#include<stdio.h>
main()
{
variable declarations */
int i,j,n,k,m,jmax,nm;
float D[3][3],d[3],x,s[3],st;
declaration of sub-functions */
int max();
FILE *FP,*fp;
n=2;
the equation is [D][s]=[d] */
read the matrix [D] and [d] */
D[0][0]=3.0;
D[0][1]=2.0;
D[0][2]=1.1;
D[1][0]=6.0;
D[1][1]=2.0;
D[1][2]=1.;

D[2][0]=1.0;
D[2][1]=4.0;
D[2][2]=2.0;
d[0]=7.65;
d[1]=13.5;
d[2]=16.0;
for(j=0;j<=2;j++)
{
printf(" %f %f %f
%f\n",D[j][0],D[j][1],D[j][2],d[j]);
}
/* eliminate column by column */
for(k=0;k<=n-1;k++)
{ nm=-1;
/* find the largest element in the column */
for(i=k;i<=n;i++)
{ nm=nm+1; s[nm]=D[i][k];}
/* call the function "max" to get the maximum value in [s] */
jmax=max(nm,s);
/* if the largest element is not in the k'th row , exchange the rows on the
LHS and RHS* /
if(jmax>0)
{
for(i=0;i<=n;i++)
{ s[i]=D[k][i];
D[k][i]=D[k+jmax][i]; D[k+jmax][i]=s[i];
}
st=d[k]; d[k]=d[k+jmax];d[k+jmax]=st;
}
/* eliminate the column using this pivoted row */
for(j=k+1;j<=n;j++)
{
x=D[j][k]/D[k][k];
for(i=k;i<=n;i++)
{
D[j][i]=D[j][i]-x*D[k][i];
}
d[j]=d[j]-d[k]*x;
}
/* print the matrix as the elimination progress */
printf("\n");
for(m=0;m<=2;m++)
{
printf(" %f %f %f
%f\n",D[m][0],D[m][1],D[m][2],d[m]);
}
}
/* find the solution by back substitution */
printf("The solution\n");
for(i=n;i>=0;i--)
{ x=0.0;
for(j=i+1;j<=n;j++)
{ x=x+D[i][j]*s[j];}
s[i]=(d[i]-x)/D[i][i];
printf(" %d %f \n", i,s[i]);
}
}
/* this sub-function called by "main" to calculate the maximum value in an array
.

The function receives a one dimensional array and returns the index correspondin
g
to the maximum value in the array. Note that since this function "returns" a var
iable
it has to have the same "type" as the variable */
int max(int nm,float s[])
{
int j,jmax;
float smax;
jmax=0;
/* start with the assuption that the first element is the largest */
smax=s[0];
/* go through the array sequentially */
for(j=1;j<=nm;j++)
{
/* if any of the elements are larger then set "jmax" to that element */
if(s[j]>smax)
{ jmax=j; smax=s[j];}
/*return the index corresponding to the largest value to the main program.*/
return jmax;
}
}
4. Solution of a set of linear equation by LU decomposition.
-----------------------------------------------------------/* Solution of a set of linear equation by LU decompostion */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
main()
{
/* Variable declarations */
int i,j,n,k,m;
float D[3][3],d[3],x,s[3],y[3];
FILE *FP,*fp1;
n=2;
/* the equation is [D][s]=[d] */
/* read the matrix [D] and [d] */
D[0][0]=3.0;
D[0][1]=2.0;
D[0][2]=1.1;
D[1][0]=6.0;
D[1][1]=2.0;
D[1][2]=1.;
D[2][0]=1.0;
D[2][1]=4.0;
D[2][2]=2.0;
d[0]=7.65;
d[1]=13.5;
d[2]=16.0;
/* print the matrix elements and the RHS on the screen */
for(j=0;j<=2;j++)
{
printf(" %f %f %f
%f\n",D[j][0],D[j][1],D[j][2],d[j]);
}

/* eliminate column by column to construct the upper triangular matrix*/


for(k=0;k<=n-1;k++)
{
for(j=k+1;j<=n;j++)
{
/* to eliminate the kth column, subtract from all rows j >i k,
the elements of the kth row, multiplied by the factor "x".
This factor is the ratio of kth element of the jth row with the
kth diagonal element */
x=D[j][k]/D[k][k];
for(i=k;i<=n;i++)
{
D[j][i]=D[j][i]-x*D[k][i];
}
/* The factor "x" is then [j,k] element of the lower triangular matrix */
D[j][k]=x;
}
/* print the matrix as it changes */
printf("\n");
for(m=0;m<=2;m++)
{
printf(" %f %f %f
%f\n",D[m][0],D[m][1],D[m][2],d[m]);
}
}
/* the forward substituion */
for(i=0;i<=n;i++)
{ x=0.0;
for(j=0;j<=i-1;j++)
{ x=x+D[i][j]*y[j];}
y[i]=(d[i]-x);
printf(" %d %f \n", i,y[i]);
}
/* the backward substitution */
printf("The solution\n");
for(i=n;i>=0;i--)
{ x=0.0;
for(j=i+1;j<=n;j++)
{ x=x+D[i][j]*s[j];}
s[i]=(y[i]-x)/D[i][i];
printf(" %d %f \n", i,s[i]);
}
}
********************************************************************************
***************************************
Sample Programs -4
********************************************************************************
***************************************
1.To compute the integral of a function using Gauss quadrature method.
---------------------------------------------------------------------/* To compute the integral of a function using Gauss quadrature method */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* define paramter constants */


#define pi 4*atan(1.0)
#define EPS 3.0e-11
/* declare the routine that compute the points at which the
function value to be evaluated and the corresponding weights */
void gauleg(float x1, float x2, float x[], float w[], int n);
main()
{
/* variable declarations */
FILE *fp1;
int i,j,Npoints,n;
/* also specify the upper and lower limit of the integral */
float *w,*x,upper_lmt=1.0,lower_lmt=.0,S;
char fname[20];
printf("\n Here, upper limit=%f; lower limit=%f\n",upper_lmt,lower_lmt);
/* Read from the screen the number of points at which the function has to be eva
luated */
printf("\n Enter no of gausleg pts you want:");
scanf("%d",&Npoints);
/* Allocate memory to store the abscissa and the corresponding weigths */
w=(float *)malloc((Npoints+2)*sizeof(float));
x=(float *)malloc((Npoints+2)*sizeof(float));
n=Npoints;
for(i=0;i<=Npoints;i++)
{
x[i]=0.0; w[i]=0.0;
}
/* Call the routine to generate the abscissa and weights. We pass
the lower and upper limit and the number of points required, to this program.
the routine returns the abscissa and weights in the pointer arrays */
gauleg(lower_lmt,upper_lmt,x,w,Npoints);
/* here is a way to generate the data file name. the name of the file here will
be
"gauslegNpoints.dat" with "Npoints" replaced by its numerical value */
sprintf(fname,"gausleg%d.dat",Npoints);
fp1=fopen(fname,"w");
for(i=1;i<=Npoints;i++)
{
fprintf(fp1,"%f %f\n",x[i],w[i]);
}
fclose(fp1);
/* compute the integral as the sum of the function values multiplied by the
weights */
S=0.0;
for(i=1;i<=Npoints;i++)
{ S=S+w[i]*pow(x[i],2)*exp(-2.0*x[i]);}
printf("%d %f\n",Npoints,S);
}
/* the function to genearate the abscissa and weights using
Gauss-Legandere qudrature rules */
void gauleg(float x1, float x2, float x[], float w[], int n)
{

int m,j,i;
double z1,z,xm,xl,pp,p3,p2,p1;
m=(n+1)/2;
xm=0.5*(x2+x1);
xl=0.5*(x2-x1);
/* find m zeros of the Legandere polynomial in the interval -1 to +1 */
for (i=1;i<=m;i++) {
z=cos(3.141592654*(i-0.25)/(n+0.5));
do {
p1=1.0;
p2=0.0;
for (j=1;j<=n;j++) {
p3=p2;
p2=p1;
p1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j;
}
pp=n*(z*p1-p2)/(z*z-1.0);
z1=z;
z=z1-p1/pp;
} while (fabs(z-z1) > EPS);
/* rescale the values to the limits required */
x[i]=xm-xl*z;
x[n+1-i]=xm+xl*z;
/* calculate the weight */
w[i]=2.0*xl/((1.0-z*z)*pp*pp);
w[n+1-i]=w[i];
}
}
#undef EPS
2. Interpolation by Newton's divided difference formula______________Datafile- d
ata.dat
--------------------------------------------------------------------------------------0.60000002
0.75000002
1.05928254
1.11524534
1.49329114
1.84503245
2.14226007
2.39050388
2.72717857
2.80259895

0.518823624
0.718823624
0.637418389
0.310572922
0.634586275
0.195216343
0.358885348
-0.136540428
-0.0872502401
-0.00997328665

#include<math.h>
#include<stdio.h>
main()
{
int i,j,n,k,dk;
float x1,x[8],f[8],y,df,df1,x0,xd,dt[8][8],pr,der;
FILE *FP;
/* Open the data file to be interpolated */
FP=fopen ("data.dat","r");
/* Read the data till the end of the file */
i=0;

while(!feof(FP))
{fscanf(FP,"%f %f \n",&x[i],&f[i]); i++;}
fclose(FP);
n=i-1;
/* construct the divided difference table and store it in a
two dimensional array. The first index is for the order of the
divided diffrence. We store all the divided difference values
to reatin the freedom for constructing a polynomial starting
with any tabulated value and not necessarily the first one */
for(i=0;i<=n;i++)
{
dt[0][i]=f[i];
}
for(j=1;j<=n;j++)
{
for(i=0;i<=(n-j);i++)
{
dt[j][i]=(dt[j-1][i+1]-dt[j-1][i])/(x[i+j]-x[i]);
}
}
/* Use the nested form to compute the interpolated values
and write it into a file */
FP=fopen ("newton.dat","w");
for(x1=.6;x1<=4.5;x1=x1+.2)
{ y=dt[n][0];
for(k=n-1;k>=0;k--)
{
y=y*(x1-x[k])+dt[k][0];
}
fprintf(FP,"%f %f \n",x1, y);
}
fclose(FP);
/* read from the screen the point at which the derivative
has to be calculated and also the point at which we want to
enter the divied difference table */
scanf("%f %d",&xd,&dk);
der=0.0;
for(k=n-dk-1;k>=1;k--)
{
/* Use the derivative of the Newtons interpolating polynomial
to calcualte the derivative at any point */
pr=1;
for(j=0;j<=k;j++)
{
pr=pr*(xd-x[j+dk]);
}
y=0;
for(i=0;i<=k;i++)
{
y=y+1.0/(xd-x[i+dk]);
}
der=der+y*pr*dt[k+1][dk];
}
der=der+dt[1][dk];
printf("%f %f\n",xd, der);
}

3. Find the solution of a system of non-linear equations


--------------------------------------------------------/find the solution of a system of non-linear equations */
/* Standard Headers */
#include<math.h>
#include<stdio.h>
/* Declare the external function to evaluate the functions
f[i] and its first derivatives w.r.t x[j]*/
void func(float[],float[],float[][]);
main()
{
/* Declaration of the variables */
float s,x[2];
int n;
float newton();
FILE *FP,*fp1;
/* number of unknowns */
n=2;
/* read from the terminal the inital guess for each variable */
scanf("%f %f",&x[0],&x[1]);
/* pass the pointer to the external function , the initial guesses and the
number of unknowns to the routine that find the solution */
non_line_eqns(x,&func,n);
printf(" The zero is %f %f\n",x[0],x[1]);
}
/* the function to find the solution of a set of nonlinar euqations by
NR method. The pointer to the external function to evalute the equations
should be supplied */
non_line_eqns(x,function,m)
int m;
float x[m];
void function (float[], float[], float[][]);
{
int i,j,n,k,jmax,nm;
float D[m][m],d[m],s[m],st,x2[m],xx;
int max();
float e;
n=m-1;
e=1.0;
for(i=1;i<=n;i++)
{s[i]=0.0;}
function(x,d,D);
/* continue till the "x[]" values are close enough to the zeros */
while(e>.00001)
{
for(j=0;j<=1;j++)
{
printf(" %f %f %f\n",D[j][0],D[j][1],d[j]);
}
/* eliminate column by column */
for(k=0;k<=n-1;k++)
{ nm=-1;
/* find the largest element in the column */
for(i=k;i<=n;i++)
{ nm=nm+1; s[nm]=D[i][k];
printf("%d %f \n", i,s[nm]);}

/* call the function "max" to get the maximum value in [s] */


jmax=max(nm,s);
printf("%d %f \n",jmax,s[jmax]);
/* if the largest element is not in the k'th row , exchange the rows on the
LHS and RHS* /
if(jmax>0)
{
for(i=0;i<=n;i++)
{ s[i]=D[k][i];
D[k][i]=D[k+jmax][i]; D[k+jmax][i]=s[i];
}
st=d[k]; d[k]=d[k+jmax];d[k+jmax]=st;
}
/* eliminate the column using this pivoted row */
for(j=k+1;j<=n;j++)
{
xx=D[j][k]/D[k][k];
for(i=k;i<=n;i++)
{
D[j][i]=D[j][i]-xx*D[k][i];
}
d[j]=d[j]-d[k]*xx;
}
}
/* find the solution by back substitution */
for(i=n;i>=0;i--)
{ xx=0.0;
for(j=i+1;j<=n;j++)
{ xx=xx+D[i][j]*s[j];}
s[i]=(d[i]-xx)/D[i][i];
}
/* Calculate the "total error" */
for(i=0;i<=n;i++)
{x[i]=x[i]+s[i];}
function(x,d,D);
e=fabs(d[1]+d[0]);
printf("%e %e %e %e %e\n",x[0],x[1],-d[0],-d[1],e);
}
}
/* this sub-function called by "non_line_eqnsn" to calculate the maximum value i
n an array.
The function receives a one dimensional array and returns the index correspondin
g
to the maximum value in the array. Note that since this function "returns" a var
iable
it has to have the same "type" as the variable */
int max(int nm,float s[])
{
int j,jmax;
float smax;
jmax=0;
smax=s[0];
for(j=1;j<=nm;j++)
{
if(s[j]>smax)
{ jmax=j; smax=s[j];}
return jmax;
}

}
void func(float x[2], float y[2], float deriv[2][2])
{
y[0]=-(pow(x[0],2)+x[0]*x[1]-10);
y[1]=-(x[1]+3*x[0]*pow(x[1],2)-57);
deriv[0][0]=2*x[0]+x[1];
deriv[0][1]=x[0];
deriv[1][0]=3*pow(x[1],2);
deriv[1][1]=1+6*x[0]*x[1];
}
4. To compute the integral of a function using Simpsons rule
------------------------------------------------------------/* To compute the integral of a function using simpsons rule */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
/* Variable declarations */
FILE *fp1;
int i,j,Npoints,n;
float *x,xp,upper_lmt=1.0,lower_lmt=0.0,S;
char fname[20];
/* also specify the upper and lower limit of the integral */
printf("\n Here, upper limit=%f; lower limit=%f\n",upper_lmt,lower_lmt);
/* Read from the screen the number of required sub-intervals */
printf("\n Enter no of pts you want:");
scanf("%d",&Npoints);
/* allocate memory to the pointer to store the intervals */
x=(float *)malloc((Npoints+2)*sizeof(float));
/* divide the whole interval to the number of sub-intervals required */
n=Npoints;
xp=(upper_lmt-lower_lmt)/Npoints;
for(i=0;i<=Npoints;i++)
{
x[i]=lower_lmt+i*xp;
}
/* compute the integral using simpsons rule and print the result on the screen *
/
S=0.0;
for(i=0;i<=Npoints-2;i=i+2)
{ S=S+xp*(pow(x[i],2)*exp(-2.0*x[i])+
4.0*(pow(x[i+1],2)*exp(-2.0*x[i+1]))
+pow(x[i+2],2)*exp(-2.0*x[i+2]))/3.0;}
printf("%d %f\n",Npoints,S);
}
5. To compute the integral of a function using mid point rule
-------------------------------------------------------------/* To compute the integral of a function using mid point rule */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()

{
/* variable decalrations */
FILE *fp1;
int i,j,Npoints,n;
/* also specify the upper and lower limit of the integral */
float *x,xp,upper_lmt=1.0,lower_lmt=0.0,S;
char fname[20];
printf("\n Here, upper limit=%f; lower limit=%f\n",upper_lmt,lower_lmt);
/* Read from the screen the number of required sub-intervals */
printf("\n Enter no of pts you want:");
scanf("%d",&Npoints);
/* allocate memory to the pointer to store the intervals */
x=(float *)malloc((Npoints+2)*sizeof(float));
/* divide the whole interval to the number of sub-intervals required */
n=Npoints;
xp=(upper_lmt-lower_lmt)/Npoints;
for(i=0;i<=Npoints;i++)
{
x[i]=lower_lmt+i*xp;
}
/* compute the integral using mid point rule and print the result on the screen
*/
S=0.0;
for(i=0;i<=Npoints-1;i++)
{ S=S+xp*pow((x[i]+x[i+1])/2.0,2)*exp(-2.0*(x[i]+x[i+1])/2.0);}
printf("%d %f\n",Npoints,S);
}

You might also like