OpcUaCanOpen
CANopen OPC-UA server
exprtk_simple_example_10.cpp
Go to the documentation of this file.
1 /*
2  **************************************************************
3  * C++ Mathematical Expression Toolkit Library *
4  * *
5  * Simple Example 10 *
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 <cmath>
20 #include <cstdio>
21 #include <string>
22 
23 #include "exprtk.hpp"
24 
25 
26 template <typename T>
28 {
32  typedef exprtk::function_compositor<T> compositor_t;
33  typedef typename compositor_t::function function_t;
34 
35  T x = T(0);
36 
37  symbol_table_t symbol_table;
38 
39  symbol_table.add_constants();
40  symbol_table.add_variable("x",x);
41 
42  compositor_t compositor(symbol_table);
43 
44  compositor
45  .add(
46  function_t( // define function: newton_sqrt(x)
47  "newton_sqrt",
48  " switch "
49  " { "
50  " case x < 0 : null; "
51  " case x == 0 : 0; "
52  " case x == 1 : 1; "
53  " default: "
54  " ~{ "
55  " var z := 100; "
56  " var sqrt_x := x / 2; "
57  " repeat "
58  " if (equal(sqrt_x^2, x)) "
59  " break[sqrt_x]; "
60  " else "
61  " sqrt_x := (1 / 2) * (sqrt_x + (x / sqrt_x)); "
62  " until ((z -= 1) <= 0); "
63  " }; "
64  " } ",
65  "x"));
66 
67  std::string expression_str = "newton_sqrt(x)";
68 
69  expression_t expression;
70  expression.register_symbol_table(symbol_table);
71 
73  parser.compile(expression_str,expression);
74 
75  for (std::size_t i = 0; i < 100; ++i)
76  {
77  x = static_cast<T>(i);
78 
79  T result = expression.value();
80 
81  printf("sqrt(%03d) - Result: %15.13f\tReal: %15.13f\n",
82  static_cast<unsigned int>(i),
83  result,
84  std::sqrt(x));
85  }
86 }
87 
88 int main()
89 {
90  newton_sqrt<double>();
91  return 0;
92 }