File: exprtk_simple_example_11.cpp

package info (click to toggle)
exprtk 0.0.3-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 7,464 kB
  • sloc: cpp: 50,516; makefile: 38
file content (74 lines) | stat: -rw-r--r-- 2,458 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 **************************************************************
 *         C++ Mathematical Expression Toolkit Library        *
 *                                                            *
 * Simple Example 11                                          *
 * Author: Arash Partow (1999-2024)                           *
 * URL: https://www.partow.net/programming/exprtk/index.html  *
 *                                                            *
 * Copyright notice:                                          *
 * Free use of the Mathematical Expression Toolkit Library is *
 * permitted under the guidelines and in accordance with the  *
 * most current version of the MIT License.                   *
 * https://www.opensource.org/licenses/MIT                    *
 * SPDX-License-Identifier: MIT                               *
 *                                                            *
 **************************************************************
*/


#include <cstdio>
#include <string>

#include "exprtk.hpp"


template <typename T>
void square_wave2()
{
   typedef exprtk::symbol_table<T> symbol_table_t;
   typedef exprtk::expression<T>   expression_t;
   typedef exprtk::parser<T>       parser_t;

   const std::string wave_program =
      " var r := 0;                                          "
      "                                                      "
      " for (var i := 0; i < 1000; i += 1)                   "
      " {                                                    "
      "    r += (1 / (2i + 1)) * sin((4i + 2) * pi * f * t); "
      " };                                                   "
      "                                                      "
      " r *= a * (4 / pi);                                   ";

   static const T pi = T(3.141592653589793238462643383279502);

   T f = pi / T(10);
   T t = T(0);
   T a = T(10);

   symbol_table_t symbol_table;
   symbol_table.add_variable("f",f);
   symbol_table.add_variable("t",t);
   symbol_table.add_variable("a",a);
   symbol_table.add_constants();

   expression_t expression;
   expression.register_symbol_table(symbol_table);

   parser_t parser;
   parser.compile(wave_program,expression);

   const T delta = (T(4) * pi) / T(1000);

   for (t = (T(-2) * pi); t <= (T(+2) * pi); t += delta)
   {
      const T result = expression.value();
      printf("%19.15f\t%19.15f\n", t, result);
   }
}

int main()
{
   square_wave2<double>();
   return 0;
}