can u help me spot my mistake with my euler prog? I cant seem to generate the print out "n" in an increasing order, also the prog stated that "ans" was not initialised. Thx alot!!!
cpp
/*This file show main steps of Euler method for solving differential equation */
/* Complete the program and use it to solve
d y / dt = - y +1
at t = 0, y = 0.0;
At the end, compare your answer with the analytical solution
This can be done by plotting computed value of y as a function of t. On the same plot show analytical solution as a function
of t.
*/
#include<stdio.h>
#include<math.h>
/* Right hand side of the Differential equation
d y/ dx = f(x, y)
*/
double func(double x, double y);
main()
{
FILE *fpt;
int N,n;
double x, x0, xMax, y0, y, h, ans, fun;
printf("\nEnter the upper limit of Integration: ");
scanf("%lf",&xMax);
printf("\nEnter a value for h: ");
scanf("%lf",&h);
fpt = fopen("answer.data","w");
y0 = 0;
x0 = 0;
N = (double) ((xMax - x0)/ h);
/* Make y equal to initial condition at x = x0; */
y= y0;
x = x0;
for(n= -1; n <= N; n++){
fun = func( x, y);
x =x+h;
/* Euler update */
y = y + h * fun;
fscanf(fpt,"%lf %lf %lf %lf",h, n, x, ans);
fprintf(fpt,"%lf %lf %lf %lf", h, n,x, ans);
fprintf(stdout,"h =%.12lf n=%.12lf t=%.12lf y=%.12lf\n",h,n,x,ans);
}
fclose(fpt);
}
/* Print your data to a file */
double func(double x, double y)
{
double ans;
ans = -y +1;
return ans;
}
MOD EDIT: Please
Thanks, gabehabe