Data output to display lines

So I've created a program to estimate ln2, and using N=75000, the output file/data is really large because the program displays every line (N=1 to N=75000).

I was wondering if there is a way to edit the program such that it displays every other line or every 'x' line where x can be any number !=1 or even something like every prime number line, or even every power to 2 line.

I am fairly new to programming so any help is appreciated.

Thanks

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Here begins estimateln2.cc
// A Monteo Carlo method to calculate the value for ln(2) to 2dp
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <time.h> // Library containing time
using namespace std;

#define ranf() ((double)rand() / (double)RAND_MAX);
// RAND_MAX used for a more efficient method of gaining a number of [0,1)

int main(int argc, char* argv[])
{
 int outcome = 0;
 int N=75000;
 int seed = time(NULL) ; // To produce a random seed every time
 double x;
 double y;
 double integral; // Relates to what the ratio actually means

if(argc>1) {
sscanf( argv[1], "%d", &N ) ; // Put the 1st command-line argument in N
}
if(argc>2) {
sscanf( argv[2], "%d", &seed ) ; // Put the 2nd argument in seed
}

// Write out a summary of parameters
cout << "# " << argv[0] << "\tN=" << N << "\tseed=" << seed << endl ;

// Initialise random number generator
srandom(seed);

// Perform N experiments
for(int n=1; n<=N; n++) {
  x = ranf(); // ranf() returns a real number in [0,1)
  y = ranf();

  x += 1.0;
  outcome += ( x*y <= 1.0 ) ? 1 : 0; // Using y = 1/x as the boundary condition
  // Note using '+=' to define less variables a += 1 means a = a + 1

// Integer variables must be converted (cast) for correct division
  integral = (double)outcome/(double)n;
  cout << "Iteration: " << n << "\tx: " << x << "\ty: " << y << "\tIntegral: " << integral << endl; // Display iteration number, coordinates of point, and ratio
}

 cout.setf(ios::fixed | ios::showpoint);
 cout.precision(2);
 cout << "ln2 = " << integral << " to 2dp" << endl; // Final display of ln2

return 0;
}


I believe the below is where I need to change 'n' to a different code?:

1
2
  cout << "Iteration: " << n << "\tx: " << x << "\ty: " << y << "\tIntegral: " << integral << endl; // Display iteration number, coordinates of point, and ratio
}
Last edited on
Topic archived. No new replies allowed.