ECF 1.5
expression_evaluation.cpp
1#include <ECF_base.h>
2#include "expression_evaluation.h"
3namespace utility{
4 double evaluateExpression(const std::map<std::string,double>& variables, std::string expression)
5 {
6 std::stack<std::string> operators;
7 std::stack<double> values;
8 std::vector<std::string> splitsContainer;
9 boost::split(splitsContainer,expression,boost::is_any_of(" "));
10 for(uint i = 0; i < splitsContainer.size(); i++) {
11 if(existingOperators.count(splitsContainer[i])) {
12 operators.push(splitsContainer[i]);
13 }
14 else if(variables.find(splitsContainer[i]) != variables.end()) {
15 values.push(variables.at(splitsContainer[i]));
16 }
17 else if(splitsContainer[i] == "(") {
18 continue;
19 }
20 else if(splitsContainer[i] == ")") {
21 if(operators.empty()) {
22 break;
23 }
24 std::string op = operators.top();
25 operators.pop();
26 double numericalV = values.top();
27 values.pop();
28 if(op == "+") {
29 numericalV = values.top() + numericalV;
30 values.pop();
31 }
32 else if(op == "-") {
33 numericalV = values.top() - numericalV;
34 values.pop();
35 }
36 else if(op == "*") {
37 numericalV = values.top() * numericalV;
38 values.pop();
39 }
40 else if(op == "/") {
41 numericalV = values.top() / numericalV;
42 values.pop();
43 }
44 else if(op == "^") {
45 numericalV = std::pow(values.top(), numericalV);
46 values.pop();
47 }
48 else if(op == "max") {
49 numericalV = std::max(values.top(),numericalV);
50 values.pop();
51 }
52 else if(op == "min") {
53 numericalV = std::min(values.top(),numericalV);
54 values.pop();
55 }
56 else if(op == "sin") {
57 numericalV = std::sin(numericalV);
58 }
59 else if(op == "cos") {
60 numericalV = std::cos(numericalV);
61 }
62 else if(op == "sqrt") {
63 numericalV = std::sqrt(numericalV);
64 }
65 else if(op == "ln") {
66 numericalV = std::log(numericalV);
67 }
68 values.push(numericalV);
69 }
70 else {
71 double numericalV;
72 try{
73 numericalV = str2dbl(splitsContainer[i]);
74 values.push(numericalV);
75 }catch(std::exception& ex) {
76 std::cerr << "Nešto nije u redu. Nisam mogao obraditi: " << splitsContainer[i] << '\n';
77 }
78 }
79 }
80 return values.top();
81 }
82}