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

Go to the source code of this file.

Functions

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

Function Documentation

◆ main()

int main ( )

Definition at line 89 of file exprtk_nthroot_bisection.cpp.

90{
91 nthroot_via_bisection<double>();
92 return 0;
93}

◆ nthroot_via_bisection()

template<typename T >
void nthroot_via_bisection ( )

Definition at line 28 of file exprtk_nthroot_bisection.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 const std::string nthroot_via_bisection_program =
37 " for (var x := -30; x <= 30; x += 1) "
38 " { "
39 " println('[', x, ']', "
40 " ' sqrt = ', nthroot(x,2), "
41 " ' cbrt = ', nthroot(x,3)); "
42 " } ";
43
45
46 symbol_table_t symbol_table;
47 symbol_table.add_function("println",println);
48
49 compositor_t compositor(symbol_table);
50
51 // define function: nthroot(x,n)
52 compositor.add(
53 function_t("nthroot")
54 .var("x")
55 .var("n")
56 .expression
57 (
58 " if (abs(frac(n)) > 0) "
59 " return [null]; "
60 " else if (x < 0 and (n % 2 == 0)) "
61 " return [null]; "
62 " "
63 " var lo := min(0,x); "
64 " var hi := max(0,x); "
65 " "
66 " while (true) "
67 " { "
68 " var mid := avg(lo,hi); "
69 " var y := pow(mid,n); "
70 " "
71 " if (equal(y, x)) "
72 " break [mid]; "
73 " else if (y < x) "
74 " lo := mid; "
75 " else "
76 " hi := mid; "
77 " }; "
78 ));
79
80 expression_t expression;
81 expression.register_symbol_table(symbol_table);
82
83 parser_t parser;
84 parser.compile(nthroot_via_bisection_program, expression);
85
86 expression.value();
87}