OpcUaCanOpen
CANopen OPC-UA server
exprtk_simple_example_04.cpp
Go to the documentation of this file.
1 /*
2  **************************************************************
3  * C++ Mathematical Expression Toolkit Library *
4  * *
5  * Simple Example 4 *
6  * Author: Arash Partow (1999-2019) *
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 
18 
19 #include <cstdio>
20 #include <string>
21 
22 #include "exprtk.hpp"
23 
24 
25 template <typename T>
26 void fibonacci()
27 {
31  typedef exprtk::function_compositor<T> compositor_t;
32  typedef typename compositor_t::function function_t;
33 
34  compositor_t compositor;
35 
36  compositor
37  .add(
38  function_t( // define function: fibonacci(x)
39  "fibonacci",
40  " var w := 0; "
41  " var y := 0; "
42  " var z := 1; "
43  " switch "
44  " { "
45  " case x == 0 : 0; "
46  " case x == 1 : 1; "
47  " default : "
48  " while ((x -= 1) > 0) "
49  " { "
50  " w := z; "
51  " z := z + y; "
52  " y := w; "
53  " z "
54  " }; "
55  " } ",
56  "x"));
57 
58  T x = T(0);
59 
60  symbol_table_t& symbol_table = compositor.symbol_table();
61  symbol_table.add_constants();
62  symbol_table.add_variable("x",x);
63 
64  std::string expression_str = "fibonacci(x)";
65 
66  expression_t expression;
67  expression.register_symbol_table(symbol_table);
68 
70  parser.compile(expression_str,expression);
71 
72  for (std::size_t i = 0; i < 40; ++i)
73  {
74  x = static_cast<T>(i);
75 
76  T result = expression.value();
77 
78  printf("fibonacci(%3d) = %10.0f\n",
79  static_cast<int>(i),
80  result);
81  }
82 }
83 
84 int main()
85 {
86  fibonacci<double>();
87  return 0;
88 }