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

Go to the source code of this file.

Functions

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

Function Documentation

◆ linear_least_squares()

template<typename T >
void linear_least_squares ( )

Definition at line 28 of file exprtk_simple_example_16.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
34 const std::string linear_least_squares_program =
35 " if (x[] == y[]) "
36 " { "
37 " beta := (sum(x * y) - sum(x) * sum(y) / x[]) / "
38 " (sum(x^2) - sum(x)^2 / x[]); "
39 " "
40 " alpha := avg(y) - beta * avg(x); "
41 " "
42 " rmse := sqrt(sum((beta * x + alpha - y)^2) / y[]); "
43 " } "
44 " else "
45 " { "
46 " alpha := null; "
47 " beta := null; "
48 " rmse := null; "
49 " } ";
50
51 T x[] = {T( 1), T( 2), T(3), T( 4), T( 5), T(6), T( 7), T( 8), T( 9), T(10)};
52 T y[] = {T(8.7), T(6.8), T(6), T(5.6), T(3.8), T(3), T(2.4), T(1.7), T(0.4), T(-1)};
53
54 T alpha = T(0);
55 T beta = T(0);
56 T rmse = T(0);
57
58 symbol_table_t symbol_table;
59 symbol_table.add_variable("alpha", alpha);
60 symbol_table.add_variable("beta" , beta );
61 symbol_table.add_variable("rmse" , rmse );
62 symbol_table.add_vector ("x" , x );
63 symbol_table.add_vector ("y" , y );
64
65 expression_t expression;
66 expression.register_symbol_table(symbol_table);
67
68 parser_t parser;
69 parser.compile(linear_least_squares_program,expression);
70
71 expression.value();
72
73 printf("alpha: %15.12f\n", alpha);
74 printf("beta: %15.12f\n", beta );
75 printf("rmse: %15.12f\n", rmse );
76 printf("y = %15.12fx + %15.12f\n", beta, alpha);
77}

◆ main()

int main ( )

Definition at line 79 of file exprtk_simple_example_16.cpp.

80{
81 linear_least_squares<double>();
82 return 0;
83}