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 " var mean_x := avg(x); "
38 " var mean_y := avg(y); "
39 " "
40 " beta := sum((x - mean_x) * (y - mean_y)) / "
41 " sum((x - mean_x)^2); "
42 " "
43 " alpha := mean_y - beta * mean_x; "
44 " "
45 " rmse := sqrt(sum((beta * x + alpha - y)^2) / y[]); "
46 " } "
47 " else "
48 " { "
49 " alpha := null; "
50 " beta := null; "
51 " rmse := null; "
52 " } ";
53
54 T x[] = { T(1.0), T(2.0), T(3.0), T(4.0), T(5.0), T(6.0), T(7.0), T(8.0), T(9.0), T(10) };
55 T y[] = { T(8.7), T(6.8), T(6.0), T(5.6), T(3.8), T(3.0), T(2.4), T(1.7), T(0.4), T(-1) };
56
57 T alpha = T(0);
58 T beta = T(0);
59 T rmse = T(0);
60
61 symbol_table_t symbol_table;
62 symbol_table.add_variable("alpha", alpha);
63 symbol_table.add_variable("beta" , beta );
64 symbol_table.add_variable("rmse" , rmse );
65 symbol_table.add_vector ("x" , x );
66 symbol_table.add_vector ("y" , y );
67
68 expression_t expression;
69 expression.register_symbol_table(symbol_table);
70
71 parser_t parser;
72 if (!parser.compile(linear_least_squares_program,expression))
73 {
74 printf("error: %s\n",parser.error().c_str());
75 return;
76 }
77
78 expression.value();
79
80 printf("alpha: %15.12f\n", alpha);
81 printf("beta: %15.12f\n", beta );
82 printf("rmse: %15.12f\n", rmse );
83 printf("y = %15.12fx + %15.12f\n", beta, alpha);
84}

◆ main()

int main ( )

Definition at line 86 of file exprtk_simple_example_16.cpp.

87{
88 linear_least_squares<double>();
89 return 0;
90}