C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
Functions
exprtk_simple_example_10.cpp File Reference
#include <cmath>
#include <cstdio>
#include <string>
#include "exprtk.hpp"
Include dependency graph for exprtk_simple_example_10.cpp:

Go to the source code of this file.

Functions

template<typename T >
void newton_sqrt ()
 
int main ()
 

Function Documentation

◆ main()

int main ( )

Definition at line 94 of file exprtk_simple_example_10.cpp.

95{
96 newton_sqrt<double>();
97 return 0;
98}

◆ newton_sqrt()

template<typename T >
void newton_sqrt ( )

Definition at line 28 of file exprtk_simple_example_10.cpp.

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}

References exprtk::details::numeric::constant::pi.