exprtk_simple_example_04.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 4 *
  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 <string>
  19. #include "exprtk.hpp"
  20. template <typename T>
  21. void fibonacci()
  22. {
  23. typedef exprtk::symbol_table<T> symbol_table_t;
  24. typedef exprtk::expression<T> expression_t;
  25. typedef exprtk::parser<T> parser_t;
  26. typedef exprtk::function_compositor<T> compositor_t;
  27. typedef typename compositor_t::function function_t;
  28. compositor_t compositor;
  29. compositor
  30. .add(
  31. function_t( // define function: fibonacci(x)
  32. "fibonacci",
  33. " var w := 0; "
  34. " var y := 0; "
  35. " var z := 1; "
  36. " switch "
  37. " { "
  38. " case x == 0 : 0; "
  39. " case x == 1 : 1; "
  40. " default : "
  41. " while ((x -= 1) > 0) "
  42. " { "
  43. " w := z; "
  44. " z := z + y; "
  45. " y := w; "
  46. " z "
  47. " }; "
  48. " } ",
  49. "x"));
  50. T x = T(0);
  51. symbol_table_t& symbol_table = compositor.symbol_table();
  52. symbol_table.add_constants();
  53. symbol_table.add_variable("x",x);
  54. std::string expression_str = "fibonacci(x)";
  55. expression_t expression;
  56. expression.register_symbol_table(symbol_table);
  57. parser_t parser;
  58. parser.compile(expression_str,expression);
  59. for (std::size_t i = 0; i < 40; ++i)
  60. {
  61. x = static_cast<T>(i);
  62. const T result = expression.value();
  63. printf("fibonacci(%3d) = %10.0f\n",
  64. static_cast<int>(i),
  65. result);
  66. }
  67. }
  68. int main()
  69. {
  70. fibonacci<double>();
  71. return 0;
  72. }