exprtk_simple_example_08.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 8 *
  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 composite()
  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::parser_error::type err_t;
  27. typedef exprtk::function_compositor<T> compositor_t;
  28. typedef typename compositor_t::function function_t;
  29. compositor_t compositor;
  30. T x = T(1);
  31. T y = T(2);
  32. symbol_table_t& symbol_table = compositor.symbol_table();
  33. symbol_table.add_constants();
  34. symbol_table.add_variable("x",x);
  35. symbol_table.add_variable("y",y);
  36. compositor
  37. .add(
  38. function_t("f","sin(x / pi)","x")); // f(x) = sin(x / pi)
  39. compositor
  40. .add(
  41. function_t("g","3*[f(x) + f(y)]","x","y")); // g(x,y) = 3[f(x) + f(y)]
  42. std::string expression_string = "g(1 + f(x), f(y) / 2)";
  43. expression_t expression;
  44. expression.register_symbol_table(symbol_table);
  45. parser_t parser;
  46. if (!parser.compile(expression_string,expression))
  47. {
  48. printf("Error: %s\tExpression: %s\n",
  49. parser.error().c_str(),
  50. expression_string.c_str());
  51. for (std::size_t i = 0; i < parser.error_count(); ++i)
  52. {
  53. const err_t error = parser.get_error(i);
  54. printf("Error: %02d Position: %02d Type: [%14s] Msg: %s\tExpression: %s\n",
  55. static_cast<unsigned int>(i),
  56. static_cast<unsigned int>(error.token.position),
  57. exprtk::parser_error::to_str(error.mode).c_str(),
  58. error.diagnostic.c_str(),
  59. expression_string.c_str());
  60. }
  61. return;
  62. }
  63. const T result = expression.value();
  64. printf("%s = %e\n", expression_string.c_str(), result);
  65. }
  66. int main()
  67. {
  68. composite<double>();
  69. return 0;
  70. }