C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_simple_example_16.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * Simple Example 16 *
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 <cstdio>
21#include <cstdlib>
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
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}
85
86int main()
87{
88 linear_least_squares<double>();
89 return 0;
90}
void linear_least_squares()