C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
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-2024) *
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 <cmath>
21#include <cstdio>
22#include <string>
23
24#include "exprtk.hpp"
25
26
27template <typename T>
29{
30 typedef exprtk::symbol_table<T> symbol_table_t;
31 typedef exprtk::expression<T> expression_t;
32 typedef exprtk::parser<T> parser_t;
33 typedef exprtk::function_compositor<T> compositor_t;
34 typedef typename compositor_t::function function_t;
35
36 T x = T(0);
37
38 symbol_table_t symbol_table;
39
40 symbol_table.add_constants();
41 symbol_table.add_variable("x",x);
42
43 compositor_t compositor(symbol_table);
44
45 compositor.add(
46 function_t("newton_sqrt")
47 .var("x")
48 .expression
49 (
50 " switch "
51 " { "
52 " case x < 0 : null; "
53 " case x == 0 : 0; "
54 " case x == 1 : 1; "
55 " default: "
56 " { "
57 " var remaining_itrs := 100; "
58 " var sqrt_x := x / 2; "
59 " repeat "
60 " if (equal(sqrt_x * sqrt_x, x)) "
61 " break[sqrt_x]; "
62 " else "
63 " sqrt_x := (1 / 2) * (sqrt_x + (x / sqrt_x)); "
64 " until ((remaining_itrs -= 1) <= 0); "
65 " }; "
66 " } "
67 ));
68
69 const std::string expression_str = "newton_sqrt(x)";
70
71 expression_t expression;
72 expression.register_symbol_table(symbol_table);
73
74 parser_t parser;
75 parser.compile(expression_str,expression);
76
77 for (x = T(0); x < T(500); x += T(0.5))
78 {
79 const T result = expression.value();
80 const T real = std::sqrt(x);
81 const T error = std::abs(result - real);
82
83 const bool err_in_bound = error <= exprtk::details::numeric::constant::pi;
84
85 printf("sqrt(%6.2f) - Result: %15.13f\tReal: %15.13f\tError: %18.16f EIB: %c\n",
86 x,
87 result,
88 real,
89 error,
90 err_in_bound ? 'T' : 'F');
91 }
92}
93
94int main()
95{
96 newton_sqrt<double>();
97 return 0;
98}
void newton_sqrt()