exprtk_simple_example_13.cpp 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 13 *
  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. void savitzky_golay_filter()
  24. {
  25. typedef exprtk::symbol_table<T> symbol_table_t;
  26. typedef exprtk::expression<T> expression_t;
  27. typedef exprtk::parser<T> parser_t;
  28. const std::string sgfilter_program =
  29. " var weight[9] := "
  30. " { "
  31. " -21, 14, 39, "
  32. " 54, 59, 54, "
  33. " 39, 14, -21 "
  34. " }; "
  35. " "
  36. " if (v_in[] >= weight[]) "
  37. " { "
  38. " var lower_bound := trunc(weight[] / 2); "
  39. " var upper_bound := v_in[] - lower_bound; "
  40. " "
  41. " v_out := 0; "
  42. " "
  43. " for (var i := lower_bound; i < upper_bound; i += 1) "
  44. " { "
  45. " for (var j := -lower_bound; j <= lower_bound; j += 1) "
  46. " { "
  47. " v_out[i] += weight[j + lower_bound] * v_in[i + j]; "
  48. " }; "
  49. " }; "
  50. " "
  51. " v_out /= sum(weight); "
  52. " } ";
  53. const std::size_t n = 1024;
  54. std::vector<T> v_in;
  55. std::vector<T> v_out;
  56. const T pi = T(3.141592653589793238462643383279502);
  57. srand(static_cast<unsigned int>(time(0)));
  58. // Generate a signal with noise.
  59. for (T t = T(-5); t <= T(+5); t += T(10.0 / n))
  60. {
  61. T noise = T(0.5 * (rand() / (RAND_MAX + 1.0) - 0.5));
  62. v_in.push_back(sin(2.0 * pi * t) + noise);
  63. }
  64. v_out.resize(v_in.size());
  65. symbol_table_t symbol_table;
  66. symbol_table.add_vector("v_in" , v_in);
  67. symbol_table.add_vector("v_out",v_out);
  68. expression_t expression;
  69. expression.register_symbol_table(symbol_table);
  70. parser_t parser;
  71. parser.compile(sgfilter_program,expression);
  72. expression.value();
  73. for (std::size_t i = 0; i < v_out.size(); ++i)
  74. {
  75. printf("%10.6f\t%10.6f\n",v_in[i],v_out[i]);
  76. }
  77. }
  78. int main()
  79. {
  80. savitzky_golay_filter<double>();
  81. return 0;
  82. }