]> Shamusworld >> Repos - architektonas/blob - fparser/examples/example2.cc
Fixed problem with MDI activation.
[architektonas] / fparser / examples / example2.cc
1 // Simple example file for the function parser
2 // ===========================================
3 /* Note that the library has to be compiled with
4    FP_SUPPORT_FLOAT_TYPE, FP_SUPPORT_LONG_DOUBLE_TYPE and
5    FP_SUPPORT_LONG_INT_TYPE
6    preprocessor macros defined for this example to work.
7
8    Try with these input values with the different floating point parser
9    types to see the difference in accuracy:
10
11 f(x) = x + 1.234567890123456789
12 min x: 0
13 max x: 2
14 step: 1
15 */
16
17 #include "../fparser.hh"
18
19 #include <iostream>
20 #include <iomanip>
21 #include <string>
22
23 template<typename Parser>
24 void runExample(const char* valueTypeName)
25 {
26     typedef typename Parser::value_type Value_t;
27
28     std::cout << "Using " << valueTypeName << " parser." << std::endl;
29
30     Parser fparser;
31     std::string function;
32     Value_t minx, maxx, step;
33
34     fparser.AddConstant("pi", Value_t(3.1415926535897932));
35
36     std::cin.ignore();
37     while(true)
38     {
39         std::cout << "f(x) = ";
40         std::getline(std::cin, function);
41         if(std::cin.fail()) return;
42
43         int res = fparser.Parse(function, "x");
44         if(res < 0) break;
45
46         std::cout << std::string(res+7, ' ') << "^\n"
47                   << fparser.ErrorMsg() << "\n\n";
48     }
49
50     std::cout << "min x: ";
51     std::cin >> minx;
52     std::cout << "max x: ";
53     std::cin >> maxx;
54     std::cout << "step: ";
55     std::cin >> step;
56     if(std::cin.fail()) return;
57
58     Value_t vals[] = { 0 };
59     for(vals[0] = minx; vals[0] <= maxx; vals[0] += step)
60     {
61         std::cout << std::setprecision(20);
62         std::cout << "f(" << vals[0] << ") = " << fparser.Eval(vals)
63                   << std::endl;
64     }
65 }
66
67 int main()
68 {
69     int choice = 0;
70     do
71     {
72         std::cout << "1 = double, 2 = float, 3 = long double, 4 = long int: ";
73         std::cin >> choice;
74     } while(choice < 1 || choice > 4);
75
76     switch(choice)
77     {
78       case 1: runExample<FunctionParser>("double"); break;
79       case 2: runExample<FunctionParser_f>("float"); break;
80       case 3: runExample<FunctionParser_ld>("long double"); break;
81       case 4: runExample<FunctionParser_li>("long int"); break;
82     }
83
84     return 0;
85 }