C++ Mathematical Expression Toolkit (ExprTk)
release
Toggle main menu visibility
Loading...
Searching...
No Matches
exprtk
exprtk_simple_example_04.cpp
Go to the documentation of this file.
1
/*
2
**************************************************************
3
* C++ Mathematical Expression Toolkit Library *
4
* *
5
* Simple Example 04 *
6
* Author: Arash Partow (1999-2025) *
7
* URL: https://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
* https://www.opensource.org/licenses/MIT *
14
* SPDX-License-Identifier: MIT *
15
* *
16
**************************************************************
17
*/
18
19
20
#include <cstdio>
21
#include <string>
22
23
#include "
exprtk.hpp
"
24
25
26
template
<
typename
T>
27
void
fibonacci
()
28
{
29
typedef
exprtk::symbol_table<T>
symbol_table_t;
30
typedef
exprtk::expression<T>
expression_t;
31
typedef
exprtk::parser<T>
parser_t;
32
typedef
exprtk::function_compositor<T>
compositor_t;
33
typedef
typename
compositor_t::function function_t;
34
35
T x = T(0);
36
37
compositor_t compositor;
38
39
compositor.add(
40
function_t(
"fibonacci"
)
41
.var(
"x"
)
42
.expression
43
(
44
" switch "
45
" { "
46
" case x == 0 : 0; "
47
" case x == 1 : 1; "
48
" default : "
49
" { "
50
" var prev := 0; "
51
" var curr := 1; "
52
" while ((x -= 1) > 0) "
53
" { "
54
" var temp := prev; "
55
" prev := curr; "
56
" curr += temp; "
57
" }; "
58
" }; "
59
" } "
60
));
61
62
symbol_table_t& symbol_table = compositor.symbol_table();
63
symbol_table.add_constants();
64
symbol_table.add_variable(
"x"
,x);
65
66
std::string expression_str =
"fibonacci(x)"
;
67
68
expression_t expression;
69
expression.register_symbol_table(symbol_table);
70
71
parser_t parser;
72
parser.compile(expression_str,expression);
73
74
for
(std::size_t i = 0; i < 40; ++i)
75
{
76
x =
static_cast<
T
>
(i);
77
78
const
T result = expression.value();
79
80
printf(
"fibonacci(%3d) = %10.0f\n"
,
81
static_cast<
int
>
(i),
82
result);
83
}
84
}
85
86
int
main
()
87
{
88
fibonacci<double>
();
89
return
0;
90
}
exprtk::expression
Definition
exprtk.hpp:21832
exprtk::function_compositor
Definition
exprtk.hpp:43057
exprtk::parser
Definition
exprtk.hpp:22525
exprtk::symbol_table
Definition
exprtk.hpp:20090
exprtk.hpp
fibonacci
void fibonacci()
Definition
exprtk_simple_example_04.cpp:27
main
int main()
Definition
exprtk_simple_example_04.cpp:86
Generated by
1.17.0