sperment.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc4000/spring2026/notes/ch3/code/sperment.cpp
 
#include <iostream>
#include <cstdlib>
#include <unistd.h>


using namespace std;

void Report(pid_t myPid);
long double Pi(int iterations);

int main() {

    srand(time(nullptr));
    pid_t myPid{getpid()};

    Report(myPid);

    cout << "pi = " << Pi(10'000'000) << endl;

    Report(myPid);
  
    return 0;
}

void Report(pid_t myPid){
    cout << endl;
    string cmd = "grep ctxt /proc/" + to_string(myPid) + "/status";
    system(cmd.c_str());
    cout << endl;
}

long double Pi(int iterations){
    long double  pi{0};

    long long count{0};
    long double  x, y;
    for(int i = 0 ; i < iterations; ++i) {
       x = rand() / static_cast<long double>(RAND_MAX);
       y = rand() / static_cast<long double>(RAND_MAX);
       if (x*x + y*y <= 1) {
          ++count;
       }
    }

    return static_cast<long double>(count)
           / static_cast<long double>(iterations) * 4;
}