C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_nthroot_bisection.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Nth-Root via Bisection Method *
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 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}
88
89int main()
90{
91 nthroot_via_bisection<double>();
92 return 0;
93}
void nthroot_via_bisection()