exprtk_simple_example_17.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 17 *
  6. * Author: Arash Partow (1999-2020) *
  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. #include <cstdio>
  18. #include <cstdlib>
  19. #include <ctime>
  20. #include <string>
  21. #include "exprtk.hpp"
  22. template <typename T>
  23. struct rnd_01 : public exprtk::ifunction<T>
  24. {
  25. using exprtk::ifunction<T>::operator();
  26. rnd_01() : exprtk::ifunction<T>(0)
  27. { ::srand(static_cast<unsigned int>(time(NULL))); }
  28. inline T operator()()
  29. {
  30. // Note: Do not use this in production
  31. // Result is in the interval [0,1)
  32. return T(::rand() / T(RAND_MAX + 1.0));
  33. }
  34. };
  35. template <typename T>
  36. void monte_carlo_pi()
  37. {
  38. typedef exprtk::symbol_table<T> symbol_table_t;
  39. typedef exprtk::expression<T> expression_t;
  40. typedef exprtk::parser<T> parser_t;
  41. const std::string monte_carlo_pi_program =
  42. " var experiments[5 * 10^7] := [(rnd_01^2 + rnd_01^2) <= 1]; "
  43. " 4 * sum(experiments) / experiments[]; ";
  44. rnd_01<T> rnd01;
  45. symbol_table_t symbol_table;
  46. symbol_table.add_function("rnd_01",rnd01);
  47. expression_t expression;
  48. expression.register_symbol_table(symbol_table);
  49. parser_t parser;
  50. parser.compile(monte_carlo_pi_program,expression);
  51. const T approximate_pi = expression.value();
  52. const T real_pi = T(3.141592653589793238462643383279502); // or close enough...
  53. printf("pi ~ %20.17f\terror: %20.17f\n",
  54. approximate_pi,
  55. std::abs(real_pi - approximate_pi));
  56. }
  57. int main()
  58. {
  59. monte_carlo_pi<double>();
  60. return 0;
  61. }