exprtk_simple_example_02.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 2 *
  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 square_wave()
  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. const std::string expr_string =
  27. "a*(4/pi)*"
  28. "((1 /1)*sin( 2*pi*f*t)+(1 /3)*sin( 6*pi*f*t)+"
  29. " (1 /5)*sin(10*pi*f*t)+(1 /7)*sin(14*pi*f*t)+"
  30. " (1 /9)*sin(18*pi*f*t)+(1/11)*sin(22*pi*f*t)+"
  31. " (1/13)*sin(26*pi*f*t)+(1/15)*sin(30*pi*f*t)+"
  32. " (1/17)*sin(34*pi*f*t)+(1/19)*sin(38*pi*f*t)+"
  33. " (1/21)*sin(42*pi*f*t)+(1/23)*sin(46*pi*f*t)+"
  34. " (1/25)*sin(50*pi*f*t)+(1/27)*sin(54*pi*f*t))";
  35. static const T pi = T(3.141592653589793238462643383279502);
  36. const T f = pi / T(10);
  37. const T a = T(10);
  38. T t = T(0);
  39. symbol_table_t symbol_table;
  40. symbol_table.add_variable("t",t);
  41. symbol_table.add_constant("f",f);
  42. symbol_table.add_constant("a",a);
  43. symbol_table.add_constants();
  44. expression_t expression;
  45. expression.register_symbol_table(symbol_table);
  46. parser_t parser;
  47. parser.compile(expr_string,expression);
  48. const T delta = (T(4) * pi) / T(1000);
  49. for (t = (T(-2) * pi); t <= (T(+2) * pi); t += delta)
  50. {
  51. const T result = expression.value();
  52. printf("%19.15f\t%19.15f\n", t, result);
  53. }
  54. }
  55. int main()
  56. {
  57. square_wave<double>();
  58. return 0;
  59. }