OpcUaCanOpen
CANopen OPC-UA server
exprtk_simple_example_17.cpp
Go to the documentation of this file.
1 /*
2  **************************************************************
3  * C++ Mathematical Expression Toolkit Library *
4  * *
5  * Simple Example 17 *
6  * Author: Arash Partow (1999-2019) *
7  * URL: http://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  * http://www.opensource.org/licenses/MIT *
14  * *
15  **************************************************************
16 */
17 
18 
19 #include <cstdio>
20 #include <cstdlib>
21 #include <ctime>
22 #include <string>
23 
24 #include "exprtk.hpp"
25 
26 
27 template <typename T>
28 struct rnd_01 : public exprtk::ifunction<T>
29 {
31 
32  rnd_01() : exprtk::ifunction<T>(0)
33  { ::srand(static_cast<unsigned int>(time(NULL))); }
34 
35  inline T operator()()
36  {
37  // Note: Do not use this in production
38  // Result is in the interval [0,1)
39  return T(::rand() / T(RAND_MAX + 1.0));
40  }
41 };
42 
43 template <typename T>
45 {
49 
50  std::string monte_carlo_pi_program =
51  " var experiments[5 * 10^7] := [(rnd_01^2 + rnd_01^2) <= 1]; "
52  " 4 * sum(experiments) / experiments[]; ";
53 
54  rnd_01<T> rnd01;
55 
56  symbol_table_t symbol_table;
57  symbol_table.add_function("rnd_01",rnd01);
58 
59  expression_t expression;
60  expression.register_symbol_table(symbol_table);
61 
63  parser.compile(monte_carlo_pi_program,expression);
64 
65  const T approximate_pi = expression.value();
66 
67  const T real_pi = T(3.141592653589793238462643383279502); // or close enough...
68 
69  printf("pi ~ %20.17f\terror: %20.17f\n",
70  approximate_pi,
71  std::abs(real_pi - approximate_pi));
72 }
73 
74 int main()
75 {
76  monte_carlo_pi<double>();
77  return 0;
78 }