C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_montecarlo_pi.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * Approximation of Pi via Monte-Carlo Method *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <cstdlib>
22#include <ctime>
23#include <string>
24
25#include "exprtk.hpp"
26
27
28template <typename T>
29struct rnd_01 : public exprtk::ifunction<T>
30{
31 using exprtk::ifunction<T>::operator();
32
34 { ::srand(static_cast<unsigned int>(time(NULL))); }
35
36 inline T operator()()
37 {
38 // Note: Do not use this in production
39 // Result is in the interval [0,1)
40 return T(::rand() / T(RAND_MAX + 1.0));
41 }
42};
43
44template <typename T>
46{
47 typedef exprtk::symbol_table<T> symbol_table_t;
48 typedef exprtk::expression<T> expression_t;
49 typedef exprtk::parser<T> parser_t;
50
51 const std::string monte_carlo_pi_program =
52 " var max_samples := 5 * 10^7; "
53 " var count := 0; "
54 " "
55 " for (var i := 0; i < max_samples; i += 1) "
56 " { "
57 " if ((rnd_01^2 + rnd_01^2) <= 1) "
58 " count += 1; "
59 " }; "
60 " "
61 " (4 * count) / max_samples; ";
62
63 rnd_01<T> rnd01;
64
65 symbol_table_t symbol_table;
66 symbol_table.add_function("rnd_01",rnd01);
67
68 expression_t expression;
69 expression.register_symbol_table(symbol_table);
70
71 parser_t parser;
72 parser.compile(monte_carlo_pi_program,expression);
73
74 const T approximate_pi = expression.value();
75
76 const T real_pi = T(3.141592653589793238462643383279502); // or close enough...
77
78 printf("pi ~ %20.17f\terror: %20.17f\n",
79 approximate_pi,
80 std::abs(real_pi - approximate_pi));
81}
82
83int main()
84{
85 monte_carlo_pi<double>();
86 return 0;
87}
ifunction(const std::size_t &pc)
Definition exprtk.hpp:19545
void monte_carlo_pi()
int main()