Skip to content

Commit

Permalink
Adding pi sim
Browse files Browse the repository at this point in the history
  • Loading branch information
gvegayon committed Sep 13, 2024
1 parent e1d633c commit 6c95106
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 1 deletion.
37 changes: 37 additions & 0 deletions 05-cpp/pi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <vector>
#include <random> // <1>
int main() {

// Setting the seed
std::mt19937 rng_engine; // <2>
rng_engine.seed(123); // <2>

std::uniform_real_distribution<double> dist(-1.0, 1.0); // <3>

// Number of simulations
size_t n_sims = 5e6;

// Defining the data
double pi_approx = 0.0;
for (size_t i = 0u; i < n_sims; ++i)
{

// Generating a point in the unit square
double x = dist(rng_engine);
double y = dist(rng_engine);

double dist = std::sqrt(
std::pow(x, 2.0) + std::pow(y, 2.0) // <2>
);

// Checking if the point is inside the unit circle
if (dist <= 1.0)
pi_approx += 1.0;

}

printf("pi approx to %.4f\n", 4.0*pi_approx/n_sims);

return 0;

}
82 changes: 81 additions & 1 deletion 05-cpp/slides.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -231,4 +231,84 @@ g++ -std=c++14 person.cpp -o person
./person
```

Notice that the destroyer is called when `p1` and `p2` go out of scope (in reverse order).
Notice that the destroyer is called when `p1` and `p2` go out of scope (in reverse order).

# Compared with R {background-color="black"}

## Simulating pi

$A = \pi r^2$, thus $\pi = \frac{A}{r^2}$.

```{r}
#| eval: true
#| echo: true
#| label: pi-sim-r
#| message: true
my_pi_sim <- function(n) {
xy <- matrix(runif(n*2, min=-1, max=1), ncol = 2)
message(
sprintf(
"pi approx to: %.4f",
mean(sqrt(rowSums(xy^2)) <= 1) * 4
)
)
}
set.seed(331)
my_pi_sim(1e6)
```

## Simulating pi in C++

::: {layout-ncol="2"}
```cpp
#include <vector>
#include <random> // <1>
int main() {

// Setting the seed
std::mt19937 rng_engine; // <2>
rng_engine.seed(123); // <2>

std::uniform_real_distribution<double> dist(-1.0, 1.0); // <3>

// Number of simulations
size_t n_sims = 5e6;

// Defining the data
double pi_approx = 0.0;
for (size_t i = 0u; i < n_sims; ++i)
{

// Generating a point in the unit square
double x = dist(rng_engine);
double y = dist(rng_engine);

double dist = std::sqrt(
std::pow(x, 2.0) + std::pow(y, 2.0) // <4>
);

// Checking if the point is inside the unit circle
if (dist <= 1.0)
pi_approx += 1.0;

}

printf("pi approx to %.4f\n", 4.0*pi_approx/n_sims);

return 0;

}
```
1. Library for random rumbers and stats distributions.
2. Random number engine (used in comb. with the distributions).
3. Uniform distribution between -1 and 1.
4. `std::pow` is the power function.
:::

```{bash}
#| eval: true
#| echo: true
g++ -std=c++14 pi.cpp -o pi
./pi
```

0 comments on commit 6c95106

Please sign in to comment.