Sunday 18 August 2019

C program - Newton Raphson method


/*newton raphson method*/
#include<stdio.h>
#include<math.h>
void
main()
{
                int count=0;
                float x0,xn,fx,dfx;
                printf("enter the guess value:");
                scanf("%f",&x0);
                /*iteration process*/
label: fx=log(x0)-x0+2;
                   dfx=pow(x0,-1)-1;
                   xn=x0-(fx/dfx);
                   if((fabs(xn-x0))<0.001)
                                   printf("\n the final root is %.4f \n",xn);
                   else
                   {x0=xn;
                   count=count+1;
                   if (count>100)
                   {
                                   printf("the solution does not converge");
                                   printf("enter a different guess value:");
                   }
                   else
                                   goto label;
                   }
}
Result1:
enter the guess value:2
 the final root is 3.1462
Press any key to continue
Result2:
enter the guess value:10

 the final root is 3.1462
Press any key to continue
/*least square fitting of a(x^b)*/
#include<stdio.h>
#include<math.h>
void
main()
{
int n,i;
float a,b,x[20],y[20],x1[20],y1[20],sx=0.0,sxx=0.0,sy=0.0,sxy=0.0,c,m,e=2.71828;
printf("enter the total number of data:");
scanf("%d",&n);
printf("enter the value of x:");
for(i=0;i<n;i++)
{
                scanf("%f",&x[i]);
}
printf("enter the values of y:");
for(i=0;i<n;i++)
{
                scanf("%f",&y[i]);
}
for(i=0;i<n;i++)
{
x1[i]=log(x[i]);
y1[i]=log(y[i]);
                sx=sx+x1[i];
                sxx=sxx+(x1[i]*x1[i]);
                sy=sy+y1[i];
                sxy=sxy+(x1[i]*y1[i]);
}
m=(n*sxy-sx*sy)/(n*sxx-sx*sx);
c=(sxx*sy-sx*sxy)/(n*sxx-sx*sx);
a=pow(e,c);
b=m;
printf("the line of least fit is:\n y=(%f)(x,(%f))\n",a,b);
}
Result:
enter the total number of data:5
enter the value of x:1 2 3 4 5
enter the values of y:20 30 38 43 48
the line of least fit is:
 y=(20.295511)(x,(0.546196))
Press any key to continue

No comments:

Post a Comment

Thanks for comment.