I am using the trapezium rule to approximate an integral, i want to output the data to a txt file so i can plot it elsewhere can anyone help me with this?
#include <iostream>
#include <cmath>
#include <fstream>
usingnamespace std ;
double func ( double x ) {
double y ;
y= exp(-x)*sin (x);
return y ;
}
int main () {
int n ; // n is the number of steps for the trapeziums
double a ;
double b;
double x0=0.0;
double x1=2.0;
int steps;
double h=(x1-x0)/steps;
double tmpA;
double A=0.0;
for ( int n=1 ; n<=steps ; n++ ) {
a= x0+ (n-1)*h;
b= a+h;
tmpA=h/2.0*(func(a) + func(b));
A=A+tmpA;
printf("%i: steps a=%f, b=%f\n",n, a,b);
}
printf("Result for %i steps: %f\n",steps,A) ;
///if your results are produced in the loop i guess
for ( int n=1 ; n<=steps ; n++ ) {
a= x0+ (n-1)*h;
b= a+h;
tmpA=h/2.0*(func(a) + func(b));
A=A+tmpA;
printf("%i: steps a=%f, b=%f\n",n, a,b);
you can add an output stream to write to your file.
ofstream out("result.txt");///result.txt will be created automatically by program
/// then include the variable in your loop to write whatever results you currently have
for ( int n=1 ; n<=steps ; n++ )
{
a= x0+ (n-1)*h;
b= a+h;
tmpA=h/2.0*(func(a) + func(b));
A=A+tmpA;
///e.g
out<</*the variable containing the results*/<<" ";
}
out.close();
printf("%i: steps a=%f, b=%f\n",n, a,b);/// this dont seem to be in main /// correct that
}
/****************************************************************/
int steps; /// error 2: this variable is not intialized it contains garbage.
double h=(x1-x0)/steps;/// note you have used the wrong thing here to intialize h.