output data to txt file

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>
#include <cmath>
#include <fstream>

using namespace 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) ;
closed account (SECMoG1T)
hi it is easy to do that the thing is i dont quite understand the trapzium rule but whatever the case is you can do it.

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
///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.
        
Last edited on
thanks a lot
Topic archived. No new replies allowed.