Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Modified Euler's Method for Numerical Solution of first order Differential Equation

Saturday, September 14, 2013

Modified Euler's Method for Numerical Solution of first order Differential Equation

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<math.h>
double dfxy(double x,double y);
FILE *fp;
int main(int argc, char* argv[])
{
double x0,y0,h,x,*xi,*yi,temp=0.0;
char c;
int n,i;
if(argc==1)
    {
    printf("\n Enter the value of h (interval-width):");
    scanf("%lf",&h);
    printf("\n Enter the initial value of x:");
    scanf("%lf",&x0);
    printf("\n Enter the initial value of y:");
    scanf("%lf",&y0);
    printf("\n Enter the value of x at which y is calculated:");
    scanf("%lf",&x);
    xi=(double *)malloc((n+1)*sizeof(double));
    yi=(double *)malloc((n+1)*sizeof(double));
    }
else if(argc==2)
    {
    /*fp=fopen(argv[1],"r");
    fscanf(fp,"%d",&n);
    fscanf(fp,"%lf",&lower_limit);
    fscanf(fp,"%lf",&upper_limit);
    xi=(double *)malloc((n+1)*sizeof(double));
    yi=(double *)malloc((n+1)*sizeof(double));*/
    }
else
    {
    printf("\n Invalid arguments, program will terminate:");
    exit(1);
    }
n=(x-x0)/h;
xi[0]=x0;
yi[0]=y0;
printf("\n\tX\t\t\tY\n");
printf("\tf(%+lf)\t\t=%+lf",xi[0],yi[0]);
i=1;
while(x0!=x)
    {
    yi[i]=yi[i-1]+dfxy(xi[i-1],yi[i-1])*h;
    x0=x0+h;
    xi[i]=x0;
    //printf("\n >>>>>>>>%lf",yi[i]);
    do
    {
    temp=yi[i];
    yi[i]=yi[i-1]+(h/2)*(dfxy(xi[i-1],yi[i-1])+dfxy(xi[i],yi[i]));
    //printf("\n >>>>>>>>%lf",yi[i]);
    }while(fabs(temp-yi[i])>0.00001);
    i++;
    xi[i]=x0;
    yi[i]=temp;
    printf("\n\tf(%+lf)\t\t=%+lf",xi[i],yi[i]);
    }
printf("\n");
return 0;
}
double dfxy(double x,double y)
    {
    return (x*x+y);
    }

No comments:

Post a Comment