]> Shamusworld >> Repos - architektonas/blob - fparser/docs/fparser.html
Fixed problem with MDI activation.
[architektonas] / fparser / docs / fparser.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <html>
3 <head>
4  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5  <link href="style.css" rel="stylesheet" type="text/css" title="normal" media=screen>
6  <title>Function Parser for C++ v4.3    : Documentation</title>
7 </head>
8
9 <body>
10 <h1>Function Parser for C++ v4.3    </h1>
11
12 <p>Authors: Juha Nieminen
13 (<a href="http://iki.fi/warp/">http://iki.fi/warp/</a>),
14 Joel Yliluoma
15 (<a href="http://iki.fi/bisqwit/">http://iki.fi/bisqwit/</a>).
16
17 <p>The usage license of this library is located at the end of this file.
18
19 <h2>Table of contents:</h2>
20
21 <ul>
22  <li><a href="#whatsnew">What's new</a>
23  <li><a href="#preface">Preface</a>
24  <li><a href="#usage">Usage</a>
25      <ul>
26       <li><a href="#parsertypes">Parser types</a>
27       <li><a href="#configuring">Configuring the compilation</a>
28       <li><a href="#copyassignment">Copying and assignment</a>
29       <li><a href="#shortdesc">Short descriptions of FunctionParser methods</a>
30       <li><a href="#longdesc">Long descriptions of FunctionParser methods</a>
31         <ul>
32           <li><a href="#longdesc_Parse"><code>Parse()</code></a>
33           <li><a href="#longdesc_setDelimiterChar"><code>setDelimiterChar()</code></a>
34           <li><a href="#longdesc_ErrorMsg"><code>ErrorMsg()</code></a>
35           <li><a href="#longdesc_GetParseErrorType"><code>GetParseErrorType()</code></a>
36           <li><a href="#longdesc_Eval"><code>Eval()</code></a>
37           <li><a href="#longdesc_EvalError"><code>EvalError()</code></a>
38           <li><a href="#longdesc_Optimize"><code>Optimize()</code></a>
39           <li><a href="#longdesc_AddConstant"><code>AddConstant()</code></a>
40           <li><a href="#longdesc_AddUnit"><code>AddUnit()</code></a>
41           <li><a href="#longdesc_AddFunction1"><code>AddFunction()</code></a> (C++ function)
42           <li><a href="#longdesc_AddFunction2"><code>AddFunction()</code></a> (FunctionParser)
43           <li><a href="#longdesc_RemoveIdentifier"><code>RemoveIdentifier()</code></a>
44           <li><a href="#longdesc_ParseAndDeduceVariables"><code>ParseAndDeduceVariables()</code></a>
45         </ul>
46      </ul>
47  <li>Syntax
48    <ul>
49      <li><a href="#literals">Numeric literals</a>
50      <li><a href="#identifiers">Identifier names</a>
51      <li><a href="#functionsyntax">The function string syntax</a>
52      <li><a href="#inlinevars">Inline variables</a>
53      <li><a href="#whitespace">Whitespace</a>
54    </ul>
55  <li>Miscellaneous
56    <ul>
57      <li><a href="#evaluationchecks">About evaluation-time checks</a>
58      <li><a href="#threadsafety">About thread safety</a>
59      <li><a href="#tipsandtricks">Tips and tricks</a>
60      <li><a href="#contact">Contacting the author</a>
61    </ul>
62 <!-- <li><a href="#algorithm">The algorithm used in the library</a> -->
63  <li><a href="#license">Usage license</a>
64 </ul>
65
66 <a name="whatsnew"></a>
67 <h2>What's new</h2>
68
69 <p>What's new in v4.3
70   <ul>
71     <li>Function syntax enhancement: Added possibility of defining new
72       variables in the function string itself. (See documentation for details.)
73     <li>Fixed some bugs in the optimizer (among others,
74       <code>"atan2(-x,-y)"</code> was being wrongly optimized into
75       <code>"atan2(x,y)"</code>
76   </ul>
77
78 <p>What's new in v4.2
79   <ul>
80     <li>The <code>Optimize()</code> method now works also with the
81       <code>float</code> and <code>long double</code> versions of the library.
82     </li>
83     <li>Some new optimizations added.</li>
84     <li>There was a call to the C99/C++0x function <code>isinf()</code> in the
85       optimizer which made it not compile with some compilers. This call has
86       been removed.</li>
87   </ul>
88
89 <p>What's new in v4.1
90   <ul>
91     <li>Official support for hexadecimal literals (for all the parser types).
92       Previously there was support only if the <code>strto...()</code> C
93       library functions happened to support them (which is a non-standard
94       extension of those functions). See documentation for details.</li>
95     <li>Significant amount of new optimizations performed by
96       <code>Parse()</code>.</li>
97     <li>Minor bugfixes.</li>
98   </ul>
99
100
101 <!-- -------------------------------------------------------------------- -->
102 <a name="preface"></a>
103 <h2>Preface</h2>
104
105 <p>This C++ library offers a class which can be used to parse and evaluate a
106 mathematical function from a string (which might be eg. requested from the
107 user). The syntax of the function string is similar to mathematical expressions
108 written in C/C++ (the exact syntax is specified later in this document).
109 The function can then be evaluated with different values of variables.
110
111 <p>For example, a function like "<code>sin(sqrt(x*x+y*y))</code>" can be
112 parsed from a string (either <code>std::string</code> or a C-style string)
113 and then evaluated with different values of <code>x</code> and <code>y</code>.
114 This library can be useful for evaluating user-inputted functions, or in
115 some cases interpreting mathematical expressions in a scripting language.
116
117 <p>This library aims for maximum speed in both parsing and evaluation, while
118 keeping maximum portability. The library should compile and work with any
119 standard-conforming C++ compiler.
120
121 <p>Different numerical types are supported: <code>double</code>,
122   <code>float</code>, <code>long double</code>, <code>long int</code>,
123   multiple-precision floating point numbers using the MPFR library, and
124   arbitrary precision integers using the GMP library. (Note that it's
125   not necessary for these two libraries to exist in the system in order
126   to use the Function Parser library with the other numerical types. Support
127   for these libraries is optionally compiled in using preprocessor settings.)
128
129
130 <!-- -------------------------------------------------------------------- -->
131 <a name="usage"></a>
132 <h2>Usage</h2>
133
134 <p>To use the <code>FunctionParser</code> class, you have to include
135 <code>"fparser.hh"</code> in your source code files which use the
136 <code>FunctionParser</code> class.
137
138 <p>If you are going to use the MPFR version of the library, you need to
139 include <code>"fparser_mpfr.hh"</code>. If you are going to use the GMP
140 version of the library, you need to include <code>"fparser_gmpint.hh"</code>.
141 (Note that support for these special parser versions needs to be specified
142 with preprocessor macros. See the <a href="#parsertypes">documentation
143 below</a> for details.)
144
145 <p>When compiling, you have to compile <code>fparser.cc</code> and
146 <code>fpoptimizer.cc</code> and link them to the main program. In many
147 developement environments it's enough to add those two files to your
148 current project (usually header files don't have to be added to the
149 project for the compilation to work).
150
151 <p>If you are going to use the MPFR or the GMP versions of the library,
152 you also need to add <code>mpfr/MpfrFloat.cc</code> or
153 <code>mpfr/GmpInt.cc</code> files to your project, respectively. Otherwise
154 they should not be added to the project.
155
156 <p>Note that part of the library source code is inside several
157 <code>.inc</code> files (these files contain auto-generated C++ code),
158 provided in the library package. These files are used by
159 <code>fparser.cc</code> and don't need to be added explicitly to the
160 project in most IDEs (such as Visual Studio). Basically, you don't need
161 to do anything with these files, other than keep them in the same directory
162 as <code>fparser.cc</code>.
163
164 <p>Simple usage example of the library:
165
166 <pre>
167     FunctionParser fp;
168     fp.Parse("sqrt(x*x + y*y)", "x,y");
169     double variables[2] = { 1.5, 2.9 };
170     double result = fp.Eval(variables);
171 </pre>
172
173 <!-- -------------------------------------------------------------------- -->
174 <a name="parsertypes"></a>
175 <h3>Parser types</h3>
176
177 <p>Different versions of the function parser class are supported, using
178   different floating point or integral types for function evaluation.
179
180 <p>All the classes other than the default one, <code>FunctionParser</code>,
181   need to be enabled at compile time by defining a preprocessor macro
182   (specified below) either in the <code>fpconfig.hh</code> file or your
183   compiler settings. (The reason for this is that all the other parser types
184   use either C99 standard libraries not yet available in the official C++
185   standard or the third-party libraries GMP and MPFR. It also makes
186   compilation faster and the resulting binary smaller when unused classes
187   are not compiled in.).
188
189 <p>Note that if you try to use the other class types without enabling them
190   with the correspondent preprocessor macro, you will get a linker error
191   (rather than a compiler error) because those classes will not have been
192   instantiated when the library was compiled.
193
194 <p>Currently the <code>Optimize()</code> method works only for the
195   <code>FunctionParser</code>, <code>FunctionParser_f</code> and
196   <code>FunctionParser_ld</code> classes. For the other types it can be
197   called but it does nothing.
198
199 <p>
200 <dl>
201   <dt><p><code>FunctionParser</code></dt>
202   <dd>
203     <p>This is the default class, which uses <code>double</code> as its
204       numerical type. This is the only class enabled by default.
205     <p>If you use some other type than this one, and you don't want this
206       version of the class compiled into the library, you can define the
207       preprocessor macro <code>FP_DISABLE_DOUBLE_TYPE</code>.
208   </dd>
209
210   <dt><p><code>FunctionParser_f</code></dt>
211   <dd>
212     <p>This parser uses <code>float</code> as its numerical type.
213     <p>The <code>FP_SUPPORT_FLOAT_TYPE</code> preprocessor macro needs to be
214       defined for this class to be enabled.
215     <p>Note that this version of the class uses C99 standard math functions
216       not yet available in all C++ compilers. Also the <code>ld</code> version
217       of the class described below use such functions.
218   </dd>
219
220   <dt><p><code>FunctionParser_ld</code></dt>
221   <dd>
222     <p>This parser uses <code>long&nbsp;double</code> as its numerical type.
223     <p>The <code>FP_SUPPORT_LONG_DOUBLE_TYPE</code> preprocessor macro needs
224       to be defined for this class to be enabled.
225   </dd>
226
227   <dt><p><code>FunctionParser_li</code></dt>
228   <dd>
229     <p>This parser uses <code>long&nbsp;int</code> as its numerical type.
230     <p>The <code>FP_SUPPORT_LONG_INT_TYPE</code> preprocessor macro needs
231       to be defined for this class to be enabled.
232     <p>Note that this version of the class uses a reduced function syntax
233       with support only for functions which are feasible to be used with
234       integral types (namely <code>abs()</code>, <code>eval()</code>,
235       <code>if()</code>, <code>min()</code> and <code>max()</code>, besides
236       basic arithmetic operators, except for the power operator).
237   </dd>
238
239   <dt><p><code>FunctionParser_mpfr</code></dt>
240   <dd>
241     <p>This parser uses <code>MpfrFloat</code> as its numerical type.
242     <p>The <code>FP_SUPPORT_MPFR_FLOAT_TYPE</code> preprocessor macro needs
243       to be defined for this class to be enabled.
244     <p>Note that to use this version of the parser,
245       <code>"fparser_mpfr.hh"</code> needs to be included.
246     <p><code>MpfrFloat</code> is an auxiliary class which uses the MPFR
247       library for multiple-precision floating point numbers. The class
248       behaves largely like a floating point type, and is declared in the
249       <code>mpfr/MpfrFloat.hh</code> file (see that file for info about
250       the public interface of the class).
251     <p>If this class is enabled, <code>mpfr/MpfrFloat.cc</code>
252       needs to be compiled into the project, as well as the GMP and MPFR
253       libraries. (With the gcc compiler this means using the linker options
254       "<code>-lgmp -lmpfr</code>".)
255   </dd>
256
257   <dt><p><code>FunctionParser_gmpint</code></dt>
258   <dd>
259     <p>This parser uses <code>GmpInt</code> as its numerical type.
260     <p>The <code>FP_SUPPORT_GMP_INT_TYPE</code> preprocessor macro needs
261       to be defined for this class to be enabled.
262     <p>Note that to use this version of the parser,
263       <code>"fparser_gmpint.hh"</code> needs to be included.
264     <p><code>GmpInt</code> is an auxiliary class which uses the GMP
265       library for arbitrary-precision integer numbers. The class
266       behaves largely like an integer type, and is declared in the
267       <code>mpfr/GmpInt.hh</code> file (see that file for info about
268       the public interface of the class).
269     <p>If this class is enabled, <code>mpfr/GmpInt.cc</code>
270       needs to be compiled into the project, as well as the GMP library.
271     <p>This version of the class also uses a reduced version of the syntax,
272       like the <code>long int</code> version.
273     <p><b>Note:</b> Since there's no upper limit to the size of GMP
274       integers, this version of the class should be used with care in
275       situations where malicious users might be able to exploit it to
276       make the program run out of memory. An example of this would be
277       a server-side application usable through the WWW.
278   </dd>
279 </dl>
280
281 <p>Note that these different classes are completely independent and
282   instances of different classes cannot be given to each other using the
283   <code>AddFunction()</code> method. Only objects of the same type can
284   be given to that method.
285
286 <p>The rest of the documentation assumes that <code>FunctionParser</code>
287   (which uses the <code>double</code> type) is used. The usage of the other
288   classes is identical except that <code>double</code> is replaced with the
289   correspondent type used by that class. (In other words, whenever the
290   rest of this documentation uses the type keyword '<code>double</code>',
291   the correspondent type should be used instead, when using another version
292   of the class.)
293
294 <!-- -------------------------------------------------------------------- -->
295 <a name="configuring"></a>
296 <h3>Configuring the compilation</h3>
297
298 <p>There is a set of precompiler options in the <code>fpconfig.hh</code> file
299 which can be used for setting certain features on or off. All of these options
300 can also be specified from the outside, using precompiler settings (eg. the
301 <code>-D</code> option in gcc), and thus it's not necessary to modify this
302 file.
303
304 <dl>
305   <dt><p><code>FP_SUPPORT_TR1_MATH_FUNCS</code> : (Default off)</dt>
306   <dd><p>Define this precompiler constant to make the library use additional
307       math functions defined in the C99 standard and the C++ TR1 standard
308       proposal (but not yet in the official C++ standard). This can make
309       evaluation faster when these functions are involved.
310     <p>The C++ TR1 math functions in question are: <code>asinh()</code>,
311       <code>acosh()</code>, <code>atanh()</code>, <code>exp2()</code> and
312       <code>log2()</code>.
313   </dd>
314
315   <dt><p><code>FP_ENABLE_EVAL</code> : (Default off)</dt>
316   <dd><p>Even though the maximum recursion level of the <code>eval()</code>
317       function is limited, it is still possible to write functions which never
318       reach this maximum recursion level but take enormous amounts of
319       time to evaluate (this can be undesirable eg. in web server-side
320       applications). For this reason this function is disabled by default.
321       You can add support for the <code>eval()</code> function by
322       defining this precompiler constant.
323   </dd>
324
325   <dt><p><code>FP_EVAL_MAX_REC_LEVEL</code> : (Default 1000)</dt>
326   <dd><p>Sets the maximum recursion level allowed for <code>eval()</code>.
327   </dd>
328
329   <dt><p><code>FP_SUPPORT_OPTIMIZER</code> : (Default on)</dt>
330   <dd><p>If you are not going to use the <code>Optimize()</code> method, you
331       can comment this line out to speed-up the compilation a bit, as
332       well as making the binary a bit smaller. (<code>Optimize()</code> can
333       still be called, but it will not do anything.)
334
335     <p>You can also disable the optimizer by specifying the
336       <code>FP_NO_SUPPORT_OPTIMIZER</code> precompiler constant in your
337       compiler settings.
338   </dd>
339
340   <dt><p><code>FP_EPSILON</code> : (Default <code>1e-14</code>)</dt>
341   <dd><p>Epsilon value used in comparison operators.
342       If this line is commented out, then no epsilon will be used.
343   </dd>
344
345   <dt><p><code>FP_USE_THREAD_SAFE_EVAL</code> : (Default off)</dt>
346   <dd><p>Define this precompiler constant to make <code>Eval()</code>
347       thread-safe. Refer to the <a href="#threadsafety">thread safety
348         section</a> later in this document for more information.
349       Note that defining this may make <code>Eval()</code> slightly slower.
350     <p>Also note that the MPFR and GMP versions of the library cannot be
351       made thread-safe, and thus this setting has no effect on them.
352   </dd>
353
354   <dt><p><code>FP_USE_THREAD_SAFE_EVAL_WITH_ALLOCA</code> : (Default off)</dt>
355   <dd><p>This is like the previous, but makes <code>Eval()</code> use the
356       <code>alloca()</code> function (instead of <code>std::vector</code>).
357       This will make it faster, but the <code>alloca()</code>
358       function is not standard and thus not supported by all compilers.
359   </dd>
360
361   <dt><p><code>FP_NO_EVALUATION_CHECKS</code> : (Default off)</dt>
362   <dd><p>If this precompiler constant is defined, no evaluation-time checks
363       will be performed. This may give a slight boost in speed in certain
364       situations. Consult the <a href="#evaluationchecks">evaluation
365         checks section</a> below for more information on this subject.
366   </dd>
367 </dl>
368
369
370 <!-- -------------------------------------------------------------------- -->
371 <a name="copyassignment"></a>
372 <h3>Copying and assignment</h3>
373
374 <p>The class implements a safe copy constructor and assignment operator.
375
376 <p>It uses the copy-on-write technique for efficiency. This means that
377   when copying or assigning a FunctionParser instance, the internal data
378   (which in some cases can be quite lengthy) is not immediately copied
379   but only when the contents of the copy (or the original) are changed.
380
381 <p>This means that copying/assigning is a very fast operation, and if
382   the copies are never modified then actual data copying never happens
383   either.
384
385 <p>The <code>Eval()</code> and <code>EvalError()</code> methods of the
386 copy can be called without the internal data being copied.
387
388 <p>Calling <code>Parse()</code>, <code>Optimize()</code> or the user-defined
389 constant/function adding methods will cause a deep-copy.
390
391
392 <!-- -------------------------------------------------------------------- -->
393 <a name="shortdesc"></a>
394 <h3>Short descriptions of FunctionParser methods</h3>
395
396 <pre>
397 int Parse(const std::string&amp; Function, const std::string&amp; Vars,
398           bool useDegrees = false);
399
400 int Parse(const char* Function, const std::string&amp; Vars,
401           bool useDegrees = false);
402 </pre>
403
404 <p>Parses the given function and compiles it to internal format.
405     Return value is -1 if successful, else the index value to the location
406     of the error.
407
408 <hr>
409 <pre>
410 void setDelimiterChar(char);
411 </pre>
412
413 <p>Sets an ending delimiter character for the function string. (See the
414     long description for more details.)
415
416 <hr>
417 <pre>
418 const char* ErrorMsg(void) const;
419 </pre>
420
421 <p>Returns an error message corresponding to the error in
422 <code>Parse()</code>, or an empty string if no such error occurred.
423
424 <hr>
425 <pre>
426 ParseErrorType GetParseErrorType() const;
427 </pre>
428
429 <p>Returns the type of parsing error which occurred. Possible return types
430     are described in the long description.
431
432 <hr>
433 <pre>
434 double Eval(const double* Vars);
435 </pre>
436
437 <p>Evaluates the function given to <code>Parse()</code>.
438
439 <hr>
440 <pre>
441 int EvalError(void) const;
442 </pre>
443
444 <p>Returns <code>0</code> if no error happened in the previous call to
445 <code>Eval()</code>, else an error code <code>&gt;0</code>.
446
447 <hr>
448 <pre>
449 void Optimize();
450 </pre>
451
452 <p>Tries to optimize the bytecode for faster evaluation.
453
454 <hr>
455 <pre>
456 bool AddConstant(const std::string&amp; name, double value);
457 </pre>
458
459 <p>Add a constant to the parser. Returns <code>false</code> if the name of
460 the constant is invalid, else <code>true</code>.
461
462 <hr>
463 <pre>
464 bool AddUnit(const std::string&amp; name, double value);
465 </pre>
466
467 <p>Add a new unit to the parser. Returns <code>false</code> if the name of
468 the unit is invalid, else <code>true</code>.
469
470 <hr>
471 <pre>
472 bool AddFunction(const std::string&amp; name,
473                  double (*functionPtr)(const double*),
474                  unsigned paramsAmount);
475 </pre>
476
477 <p>Add a user-defined function to the parser (as a function pointer).
478 Returns <code>false</code> if the name of the function is invalid, else
479 <code>true</code>.
480
481 <hr>
482 <pre>
483 bool AddFunction(const std::string&amp; name, FunctionParser&amp;);
484 </pre>
485
486 <p>Add a user-defined function to the parser (as a <code>FunctionParser</code>
487 instance). Returns <code>false</code> if the name of the function is invalid,
488 else <code>true</code>.
489
490 <hr>
491 <pre>
492 bool RemoveIdentifier(const std::string&amp; name);
493 </pre>
494
495 <p>Removes the constant, unit or user-defined function with the specified
496 name from the parser.
497
498 <hr>
499 <pre>
500 int ParseAndDeduceVariables(const std::string&amp; function,
501                             int* amountOfVariablesFound = 0,
502                             bool useDegrees = false);
503 int ParseAndDeduceVariables(const std::string&amp; function,
504                             std::string&amp; resultVarString,
505                             int* amountOfVariablesFound = 0,
506                             bool useDegrees = false);
507 int ParseAndDeduceVariables(const std::string&amp; function,
508                             std::vector&lt;std::string&gt;&amp; resultVars,
509                             bool useDegrees = false);
510 </pre>
511
512 <p>Like <code>Parse()</code>, but the variables in the function are deduced
513 automatically. The amount of found variables and the variable names themselves
514 are returned by the different versions of the function.
515
516 <!-- -------------------------------------------------------------------- -->
517 <a name="longdesc"></a>
518 <h3>Long descriptions of FunctionParser methods</h3>
519
520 <hr>
521 <a name="longdesc_Parse"></a>
522 <pre>
523 int Parse(const std::string&amp; Function, const std::string&amp; Vars,
524           bool useDegrees = false);
525
526 int Parse(const char* Function, const std::string&amp; Vars,
527           bool useDegrees = false);
528 </pre>
529
530 <p>Parses the given function (and compiles it to internal format).
531 Destroys previous function. Following calls to <code>Eval()</code> will evaluate
532 the given function.
533
534 <p>The strings given as parameters are not needed anymore after parsing.
535
536 <p>Parameters:
537
538 <table border=2>
539  <tr>
540   <td><code>Function</code></td>
541   <td>String containing the function to parse.</td>
542  </tr><tr>
543   <td><code>Vars</code></td>
544   <td>String containing the variable names, separated by commas.<br>
545       Eg. <code>"x,y"</code>, <code>"VarX,VarY,VarZ,n"</code> or
546       <code>"x1,x2,x3,x4,__VAR__"</code>.
547  </tr><tr>
548   <td><code>useDegrees</code></td>
549   <td>(Optional.) Whether to use degrees or radians in
550         trigonometric functions. (Default: radians)</td>
551  </tr>
552 </table>
553
554 <p>If a <code>char*</code> is given as the <code>Function</code> parameter,
555 it must be a null-terminated string.
556
557 <p>Variables can have any size and they are case sensitive (ie.
558 <code>"var"</code>, <code>"VAR"</code> and <code>"Var"</code> are
559 <em>different</em> variable names). Letters, digits, underscores and
560 UTF8-encoded characters can be used in variable names, but the name of
561 a variable can't begin with a digit. Each variable name can appear only
562 once in the '<code>Vars</code>' string. Function names are not legal
563 variable names.
564
565 <p>Using longer variable names causes no overhead whatsoever to the
566 <code>Eval()</code> method, so it's completely safe to use variable names
567 of any size.
568
569 <p>The third, optional parameter specifies whether angles should be
570     interpreted as radians or degrees in trigonometrical functions.
571     If not specified, the default value is radians.
572
573 <p>Return values:
574
575 <ul>
576  <li>On success the function returns <code>-1</code>.
577  <li>On error the function returns an index to where the error was found
578      (<code>0</code> is the first character, <code>1</code> the second, etc).
579      If the error was not a parsing error returns an index to the end of the
580      string.
581 </ul>
582
583 <p>Example: <code>parser.Parse("3*x+y", "x,y");</code>
584
585
586 <hr>
587 <a name="longdesc_setDelimiterChar"></a>
588 <pre>
589 void setDelimiterChar(char);
590 </pre>
591
592 <p>By default the parser expects the entire function string to be valid
593 (ie. the entire contents of the given <code>std::string</code>, or a C string
594 ending in the null character <code>'\0'</code>).
595
596 <p>If a delimiter character is specified with this function, then if it's
597 encountered at the outermost parsing level by the <code>Parse()</code>
598 function, and the input function has been valid so far, <code>Parse()</code>
599 will return an index to this character inside the input string, but rather
600 than set an error code, <code>FP_NO_ERROR</code> will be set.
601
602 <p>The idea is that this can be used to more easily parse functions which
603 are embedded inside larger strings, containing surrounding data, without
604 having to explicitly extract the function to a separate string.
605
606 <p>For example, suppose you are writing an interpreter for a scripting
607     language, which can have commands like this:
608
609 <p><code>let MyFunction(x,y) = { sin(x*x+y*y) } // A 2-dimensional function</code>
610
611 <p>Normally when parsing such a line you would have to extract the part
612 inside the curly brackets into a separate string and parse it that way.
613 With this feature what you can do instead is to set <code>'}'</code> as
614 the delimiter character and then simply give a pointer to the character
615 which comes after the <code>'{'</code>. If all goes well, the
616 <code>Parse()</code> function will return an index to the <code>'}'</code>
617 character (from the given starting point) and <code>GetParseErrorType()</code>
618 will return <code>FP_NO_ERROR</code>. You can use the return
619 value (if it's not <code>-1</code>) to jump forward in the string to the
620 delimiter character.
621
622 <p>Note that a null character (<code>'\0'</code>) or the end of the
623 <code>std::string</code> (if one was given) will still be a valid end of
624 the function string even if a delimiter character was specified. (In this
625 case <code>Parse()</code> will return <code>-1</code> if there was no error,
626 as usual.)
627
628 <p>Also note that the delimiter character cannot be any valid operator
629 or alphanumeric (including the underscore) character, nor the other
630 characters defined in the function syntax. It must be a character not
631 supported by the function parser (such as <code>'}'</code>,
632 <code>'&quot;'</code>, <code>']'</code>, etc).
633
634
635 <hr>
636 <a name="longdesc_ErrorMsg"></a>
637 <pre>
638 const char* ErrorMsg(void) const;
639 </pre>
640
641 <p>Returns a pointer to an error message string corresponding to the error
642 caused by <code>Parse()</code> (you can use this to print the proper error
643 message to the user). If no such error has occurred, returns an empty string.
644
645
646 <hr>
647 <a name="longdesc_GetParseErrorType"></a>
648 <pre>
649 ParseErrorType GetParseErrorType() const;
650 </pre>
651
652 <p>Returns the type of parse error which occurred.
653
654 <p>This method can be used to get the error type if <code>ErrorMsg()</code>
655 is not enough for printing the error message. In other words, this can be
656 used for printing customized error messages (eg. in another language).
657 If the default error messages suffice, then this method doesn't need
658 to be called.
659
660 <code>FunctionParser::ParseErrorType</code> is an enumerated type inside
661 the class (ie. its values are accessed like
662 "<code>FunctionParser::SYNTAX_ERROR</code>").
663
664 <p>The possible values for FunctionParser::ParseErrorType are listed below,
665 along with their equivalent error message returned by the
666 <code>ErrorMsg()</code> method:
667
668 <p><table border=2>
669 <tr>
670  <td><code>FP_NO_ERROR</code></td>
671  <td>If no error occurred in the previous call to <code>Parse()</code>.</td>
672 </tr><tr>
673  <td><code>SYNTAX_ERROR</code></td>
674  <td>"Syntax error"</td>
675 </tr><tr>
676  <td><code>MISM_PARENTH</code></td>
677  <td>"Mismatched parenthesis"</td>
678 </tr><tr>
679  <td><code>MISSING_PARENTH</code></td>
680  <td>"Missing ')'"</td>
681 </tr><tr>
682  <td><code>EMPTY_PARENTH</code></td>
683  <td>"Empty parentheses"</td>
684 </tr><tr>
685  <td><code>EXPECT_OPERATOR</code></td>
686  <td>"Syntax error: Operator expected"</td>
687 </tr><tr>
688  <td><code>OUT_OF_MEMORY</code></td>
689  <td>"Not enough memory"</td>
690 </tr><tr>
691  <td><code>UNEXPECTED_ERROR</code></td>
692  <td>"An unexpected error occurred. Please make a full bug report to the
693       author"</td>
694 </tr><tr>
695  <td><code>INVALID_VARS</code></td>
696  <td>"Syntax error in parameter 'Vars' given to FunctionParser::Parse()"</td>
697 </tr><tr>
698  <td><code>ILL_PARAMS_AMOUNT</code></td>
699  <td>"Illegal number of parameters to function"</td>
700 </tr><tr>
701  <td><code>PREMATURE_EOS</code></td>
702  <td>"Syntax error: Premature end of string"</td>
703 </tr><tr>
704  <td><code>EXPECT_PARENTH_FUNC</code></td>
705  <td>"Syntax error: Expecting ( after function"</td>
706 </tr><tr>
707  <td><code>UNKNOWN_IDENTIFIER</code></td>
708  <td>"Syntax error: Unknown identifier"</td>
709 </tr><tr>
710  <td><code>NO_FUNCTION_PARSED_YET</code></td>
711  <td>"(No function has been parsed yet)"</td>
712 </tr>
713 </table>
714
715
716 <hr>
717 <a name="longdesc_Eval"></a>
718 <pre>
719 double Eval(const double* Vars);
720 </pre>
721
722 <p>Evaluates the function given to <code>Parse()</code>.
723 The array given as parameter must contain the same amount of values as
724 the amount of variables given to <code>Parse()</code>. Each value corresponds
725 to each variable, in the same order.
726
727 <p>Return values:
728 <ul>
729  <li>On success returns the evaluated value of the function given to
730      <code>Parse()</code>.
731  <li>On error (such as division by 0) the return value is unspecified,
732      probably 0.
733 </ul>
734
735 <p>Example:
736
737 <p><code>double Vars[] = {1, -2.5};</code><br>
738 <code>double result = parser.Eval(Vars);</code>
739
740
741 <hr>
742 <a name="longdesc_EvalError"></a>
743 <pre>
744 int EvalError(void) const;
745 </pre>
746
747 <p>Used to test if the call to <code>Eval()</code> succeeded.
748
749 <p>Return values:
750
751 <p>If there was no error in the previous call to <code>Eval()</code>,
752 returns <code>0</code>, else returns a positive value as follows:
753 <ul>
754  <li>1: division by zero
755  <li>2: sqrt error (sqrt of a negative value)
756  <li>3: log error (logarithm of a negative value)
757  <li>4: trigonometric error (asin or acos of illegal value)
758  <li>5: maximum recursion level in <code>eval()</code> reached
759 </ul>
760
761
762 <hr>
763 <a name="longdesc_Optimize"></a>
764 <pre>
765 void Optimize();
766 </pre>
767
768 <p>This method can be called after calling the <code>Parse()</code> method.
769 It will try to simplify the internal bytecode so that it will evaluate faster
770 (it tries to reduce the amount of opcodes in the bytecode).
771
772 <p>For example, the bytecode for the function <code>"5+x*y-25*4/8"</code> will
773 be reduced to a bytecode equivalent to the function <code>"x*y-7.5"</code> (the
774 original 11 opcodes will be reduced to 5). Besides calculating constant
775 expressions (like in the example), it also performs other types of
776 simplifications with variable and function expressions.
777
778 <p>This method is quite slow and the decision of whether to use it or
779 not should depend on the type of application. If a function is parsed
780 once and evaluated millions of times, then calling <code>Optimize()</code>
781 may speed-up noticeably. However, if there are tons of functions to parse
782 and each one is evaluated once or just a few times, then calling
783 <code>Optimize()</code> will only slow down the program.
784
785 <p>Also, if the original function is expected to be optimal, then calling
786 <code>Optimize()</code> would be useless.
787
788 <p>Note: Currently this method does not make any checks (like
789 <code>Eval()</code> does) and thus things like <code>"1/0"</code> will cause
790 undefined behaviour. (On the other hand, if such expression is given to the
791 parser, <code>Eval()</code> will always give an error code, no matter what
792 the parameters.) If caching this type of errors is important, a work-around
793 is to call <code>Eval()</code> once before calling <code>Optimize()</code>
794 and checking <code>EvalError()</code>.
795
796 <p>If the destination application is not going to use this method,
797 the compiler constant <code>FP_SUPPORT_OPTIMIZER</code> can be undefined in
798 <code>fpconfig.hh</code> to make the library smaller (<code>Optimize()</code>
799 can still be called, but it will not do anything).
800
801 <p>(If you are interested in seeing how this method optimizes the opcode,
802 you can call the <code>PrintByteCode()</code> method before and after the
803 call to <code>Optimize()</code> to see the difference.)
804
805
806 <hr>
807 <a name="longdesc_AddConstant"></a>
808 <pre>
809 bool AddConstant(const std::string&amp; name, double value);
810 </pre>
811
812 <p>This method can be used to add constants to the parser. Syntactically
813     constants are identical to variables (ie. they follow the same naming
814     rules and they can be used in the function string in the same way as
815     variables), but internally constants are directly replaced with their
816     value at parse time.
817
818 <p>Constants used by a function must be added before calling
819 <code>Parse()</code> for that function. Constants are preserved between
820 <code>Parse()</code> calls in the current FunctionParser instance, so
821 they don't need to be added but once. (If you use the same constant in
822 several instances of FunctionParser, you will need to add it to all the
823 instances separately.)
824
825 <p>Constants can be added at any time and the value of old constants can
826 be changed, but new additions and changes will only have effect the next
827 time <code>Parse()</code> is called. (That is, changing the value of a constant
828 after calling <code>Parse()</code> and before calling <code>Eval()</code>
829 will have no effect.)
830
831 <p>The return value will be <code>false</code> if the '<code>name</code>' of
832 the constant was illegal, else <code>true</code>. If the name was illegal,
833 the method does nothing.
834
835 <p>Example: <code>parser.AddConstant("pi", 3.1415926535897932);</code>
836
837 <p>Now for example <code>parser.Parse("x*pi", "x");</code> will be identical
838 to the call <code>parser.Parse("x*3.1415926535897932", "x");</code>
839
840
841 <hr>
842 <a name="longdesc_AddUnit"></a>
843 <pre>
844 bool AddUnit(const std::string&amp; name, double value);
845 </pre>
846
847 <p>In some applications it is desirable to have units of measurement.
848 A typical example is an application which creates a page layout to be
849 printed. When printing, distances are usually measured in points
850 (defined by the resolution of the printer). However, it is often more
851 useful for the user to be able to specify measurements in other units
852 such as centimeters or inches.
853
854 <p>A unit is simply a value by which the preceding element is multiplied.
855 For example, if the printing has been set up to 300 DPI, one inch is
856 then 300 points (dots). Thus saying eg. <code>"5in"</code> is the same as saying
857 <code>"5*300"</code> or <code>"1500"</code> (assuming <code>"in"</code> has
858 been added as a unit with the value 300).
859
860 <p>Note that units are slightly different from a multiplication in
861 that they have a higher precedence than any other operator (except
862 parentheses). Thus for example <code>"5/2in"</code> is parsed as
863 <code>"5/(2*300)"</code>.
864 (If 5/2 inches is what one wants, it has to be written <code>"(5/2)in"</code>.)
865
866 <p>You can use the <code>AddUnit()</code> method to add a new unit. The
867 unit can then be used after any element in the function (and will work as
868 a multiplier for that element). An element is a float literal, a constant,
869 a variable, a function or any expression in parentheses. When the element
870 is not a float literal nor an expression in parentheses, there has to naturally
871 be at least one whitespace between the element and the unit (eg.
872 <code>"x in"</code>). To change the value of a unit, call
873 <code>AddUnit()</code> again with the same unit name and the new value.
874
875 <p>Unit names share the same namespace as constants, functions and
876     variables, and thus should be distinct from those.
877
878 <p>Example: <code>parser.AddUnit("in", 300);</code>
879
880 <p>Now for example the function <code>"5in"</code> will be identical to
881 <code>"(5*300)"</code>. Other usage examples include <code>"x in"</code>,
882 <code>"3in+2"</code>, <code>"pow(x,2)in"</code>, <code>"(x+2)in"</code>.
883
884
885 <hr>
886 <a name="longdesc_AddFunction1"></a>
887 <pre>
888 bool AddFunction(const std::string&amp; name,
889                  double (*functionPtr)(const double*),
890                  unsigned paramsAmount);
891 </pre>
892
893 This method can be used to add new functions to the parser. For example,
894 if you would like to add a function "<code>sqr(A)</code>" which squares the
895 value of <code>A</code>, you can do it with this method (so that you don't
896 need to touch the source code of the parser).
897
898 <p>The method takes three parameters:
899
900 <ul>
901  <li>The name of the function. The name follows the same naming conventions
902       as variable names.
903
904  <li>A C++ function, which will be called when evaluating the function
905       string (if the user-given function is called there). The C++ function
906       must have the form:
907       <p><code>double functionName(const double* params);</code>
908
909  <li>The number of parameters the function takes. 0 is a valid value
910       in which case the function takes no parameters (such function
911       should simply ignore the <code>double*</code> it gets as a parameter).
912 </ul>
913
914 <p>The return value will be <code>false</code> if the given name was invalid
915 (either it did not follow the variable naming conventions, or the name was
916 already reserved), else <code>true</code>. If the return value is
917 <code>false</code>, nothing is added.
918
919 <p>Example: Suppose we have a C++ function like this:
920
921 <p><code>double Square(const double* p)</code><br>
922 <code>{</code><br>
923 <code>&nbsp;&nbsp;&nbsp;&nbsp;return p[0]*p[0];</code><br>
924 <code>}</code>
925
926 <p>Now we can add this function to the parser like this:
927
928 <p><code>parser.AddFunction("sqr", Square, 1);</code><br>
929 <code>parser.Parse("2*sqr(x)", "x");</code>
930
931 <p>An example of a useful function taking no parameters is a function
932     returning a random value. For example:
933
934 <p><code>double Rand(const double*)</code><br>
935 <code>{</code><br>
936 <code>&nbsp;&nbsp;&nbsp;&nbsp;return drand48();</code><br
937 <code>}</code>
938
939 <p><code>parser.AddFunction("rand", Rand, 0);</code>
940
941 <p><em>Important note</em>: If you use the <code>Optimize()</code> method,
942 it will assume that the user-given function has no side-effects, that is,
943 it always returns the same value for the same parameters. The optimizer will
944 optimize the function call away in some cases, making this assumption.
945 (The <code>Rand()</code> function given as example above is one such
946 problematic case.)
947
948
949 <hr>
950 <a name="longdesc_AddFunction2"></a>
951 <pre>
952 bool AddFunction(const std::string&amp; name, FunctionParser&amp;);
953 </pre>
954
955 <p>This method is almost identical to the previous <code>AddFunction()</code>,
956 but instead of taking a C++ function, it takes another FunctionParser
957 instance.
958
959 <p>There are some important restrictions on making a FunctionParser instance
960     call another:
961
962 <ul>
963  <li>The FunctionParser instance given as parameter must be initialized
964       with a <code>Parse()</code> call before giving it as parameter. That
965       is, if you want to use the parser <code>A</code> in the parser
966       <code>B</code>, you must call <code>A.Parse()</code> before you can
967       call <code>B.AddFunction("name", A)</code>.
968
969  <li>The amount of variables in the FunctionParser instance given as
970       parameter must not change after it has been given to the
971       <code>AddFunction()</code>
972       of another instance. Changing the number of variables will result in
973       malfunction.
974
975  <li><code>AddFunction()</code> will fail (ie. return <code>false</code>)
976       if a recursive loop is
977       formed. The method specifically checks that no such loop is built.
978
979  <li>The FunctionParser instance given as parameter will <em>not</em> be
980      copied internally, only referenced. Thus the FunctionParser instance
981      given as parameter must exist for as long as the other FunctionParser
982      instance uses it.
983 </ul>
984
985 <p>Example:
986
987 <p><code>FunctionParser f1, f2;</code><br>
988 <p><code>f1.Parse("x*x", "x");</code><br>
989 <p><code>f2.AddFunction("sqr", f1);</code>
990
991 <p>This version of the <code>AddFunction()</code> method can be useful to
992 eg. chain user-given functions. For example, ask the user for a function F1,
993     and then ask the user another function F2, but now the user can
994     call F1 in this second function if he wants (and so on with a third
995     function F3, where he can call F1 and F2, etc).
996
997 <hr>
998 <a name="longdesc_RemoveIdentifier"></a>
999 <pre>
1000 bool RemoveIdentifier(const std::string&amp; name);
1001 </pre>
1002
1003 <p>If a constant, unit or user-defined function with the specified name
1004 exists in the parser, it will be removed and the return value will be
1005 <code>true</code>, else nothing will be done and the return value will be
1006 <code>false</code>.
1007
1008 <p>(Note: If you want to remove <em>everything</em> from an existing
1009 FunctionParser instance, simply assign a fresh instance to it, ie. like
1010 "<code>parser&nbsp;=&nbsp;FunctionParser();</code>")
1011
1012 <hr>
1013 <a name="longdesc_ParseAndDeduceVariables"></a>
1014 <pre>
1015 int ParseAndDeduceVariables(const std::string&amp; function,
1016                             int* amountOfVariablesFound = 0,
1017                             bool useDegrees = false);
1018 int ParseAndDeduceVariables(const std::string&amp; function,
1019                             std::string&amp; resultVarString,
1020                             int* amountOfVariablesFound = 0,
1021                             bool useDegrees = false);
1022 int ParseAndDeduceVariables(const std::string&amp; function,
1023                             std::vector&lt;std::string&gt;&amp; resultVars,
1024                             bool useDegrees = false);
1025 </pre>
1026
1027 <p>These functions work in the same way as the <code>Parse()</code> function,
1028 but the variables in the input function string are deduced automatically. The
1029 parameters are:
1030
1031 <ul>
1032  <li><code>function</code>: The input function string, as with
1033    <code>Parse()</code>.
1034  <li><code>amountOfVariablesFound</code>: If non-null, the amount of found
1035    variables will be assigned here.
1036  <li><code>resultVarString</code>: The found variables will be written to
1037    this string, in the same format as accepted by the <code>Parse()</code>
1038    function. The variable names will be sorted using the <code>&lt;</code>
1039    operator of <code>std::string</code>.
1040  <li><code>resultVars</code>: The found variables will be written to this
1041    vector, each element being one variable name. They will be sorted using
1042    the <code>&lt;</code> operator of <code>std::string</code>. (The amount
1043    of found variables can be retrieved, rather obviously, with the
1044    <code>size()</code> method of the vector.)
1045  <li><code>useDegrees</code>: As with <code>Parse()</code>.
1046 </ul>
1047
1048 <p>As with <code>Parse()</code>, the return value will be <code>-1</code> if
1049 the parsing succeeded, else an index to the location of the error. None of
1050 the specified return values will be modified in case of error.
1051
1052
1053 <!-- -------------------------------------------------------------------- -->
1054 <h2>Syntax</h2>
1055
1056 <a name="literals"></a>
1057 <h3>Numeric literals</h3>
1058
1059 <p>A numeric literal is a fixed numerical value in the input function string
1060   (either a floating point value or an integer value, depending on the parser
1061   type).
1062
1063 <p>An integer literal can consist solely of numerical digits (possibly with
1064   a preceding unary minus). For example, "<code>12345</code>".
1065
1066 <p>If the literal is preceded by the characters "<code>0x</code>", it
1067   will be interpreted as a hexadecimal literal, where digits can also include
1068   the letters from '<code>A</code>' to '<code>F</code>' (in either uppercase
1069   or lowercase). For example, "<code>0x89ABC</code>" (which corresponds to the
1070   value 563900).
1071
1072 <p>A floating point literal (only supported by the floating point type parsers)
1073   may additionally include a decimal point followed by the decimal part of the
1074   value, such as for example "<code>12.34</code>", optionally followed by a
1075   decimal exponent.
1076
1077 <p>A decimal exponent consists of an '<code>E</code>' or '<code>e</code>',
1078   followed by an optional plus or minus sign, followed by decimal digits, and
1079   indicates multiplication by a power of 10. For example, "<code>1.2e5</code>"
1080   (which is equivalent to the value 120000).
1081
1082 <p>If a floating point literal is preceded by the characters "<code>0x</code>"
1083   it will be interpreted in hexadecimal. A hexadecimal floating point
1084   literal consists of a hexadecimal value, with an optional decimal point,
1085   followed optionally by a binary exponent in base 10 (in other words, the
1086   exponent is not in hexadecimal).
1087
1088 <p>A binary exponent has the same format as a decimal exponent, except that
1089   '<code>P</code>' or '<code>p</code>' is used. A binary exponent indicates
1090   multiplication by a power of 2. For example, "<code>0xA.Bp10</code>"
1091   (which is equivalent to the value 10944).
1092
1093 <a name="identifiers"></a>
1094 <h3>Identifier names</h3>
1095
1096 <p>An identifier is the name of a function (internal or user-defined),
1097   variable, constant or unit. New identifiers can be specified with the
1098   functions described in the earlier subsections in this document.
1099
1100 <p>The name of an identifier can use any alphanumeric characters, the
1101   underscore character and any UTF8-encoded unicode character, excluding
1102   those denoting whitespace.
1103   The first character of the name cannot be a numeric digit, though.
1104
1105 <p>All functions, variables, constants and units must use unique names.
1106   It's not possible to add two different identifiers with the same name.
1107
1108
1109 <!-- -------------------------------------------------------------------- -->
1110 <a name="functionsyntax"></a>
1111 <h3>The function string syntax</h3>
1112
1113 <p>The function string understood by the class is very similar (but not
1114 completely identical in all aspects) to mathematical expressions in the
1115 C/C++ languages.
1116 Arithmetic float expressions can be created from float literals, variables
1117 or functions using the following operators in this order of precedence:
1118
1119 <p><table border=2>
1120  <tr>
1121   <td><code>()</code></td>
1122   <td>expressions in parentheses first</td>
1123  </tr><tr>
1124   <td><code>A unit</code></td>
1125   <td>a unit multiplier (if one has been added)</td>
1126  </tr><tr>
1127   <td><code>A^B</code></td>
1128   <td>exponentiation (A raised to the power B)</td>
1129  </tr><tr>
1130   <td><code>-A</code></td>
1131   <td>unary minus</td>
1132  </tr><tr>
1133   <td><code>!A</code></td>
1134   <td>unary logical not (result is 1 if <code>int(A)</code> is 0, else 0)</td>
1135  </tr><tr>
1136   <td><code>A*B  A/B  A%B</code></td>
1137   <td>multiplication, division and modulo</td>
1138  </tr><tr>
1139   <td><code>A+B  A-B</code></td>
1140   <td>addition and subtraction</td>
1141  </tr><tr>
1142   <td><code>A=B  A&lt;B  A&lt;=B<br>A!=B  A&gt;B  A&gt;=B</code></td>
1143   <td>comparison between A and B (result is either 0 or 1)</td>
1144  </tr><tr>
1145   <td><code>A&amp;B</code></td>
1146   <td>result is 1 if <code>int(A)</code> and <code>int(B)</code> differ from
1147       0, else 0.<br>
1148       Note: Regardless of the values, both operands are always
1149       evaluated. However, if the expression is optimized, it may
1150       be changed such that only one of the operands is evaluated,
1151       according to standard shortcut logical operation semantics.</td>
1152  </tr><tr>
1153   <td><code>A|B</code></td>
1154   <td>result is 1 if <code>int(A)</code> or <code>int(B)</code> differ from 0,
1155       else 0.<br>
1156       Note: Regardless of the values, both operands are always
1157       evaluated. However, if the expression is optimized, it may
1158       be changed such that only one of the operands is evaluated,
1159       according to standard shortcut logical operation semantics.</td>
1160  </tr>
1161 </table>
1162
1163 <p>(Note that currently the exponentiation operator is not supported for
1164   <code>FunctionParser_li</code> nor <code>FunctionParser_gmpint</code>.
1165   With the former the result would very easily overflow, making its
1166   usefulness questionable. With the latter it could be easily abused to
1167   make the program run out of memory; think of a function like
1168   "10^10^10^100000".)
1169
1170 <p>Since the unary minus has higher precedence than any other operator, for
1171   example the following expression is valid: <code>x*-y</code>
1172
1173 <p>The comparison operators use an epsilon value, so expressions which may
1174 differ in very least-significant digits should work correctly. For example,
1175 <code>"0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 = 1"</code> should always
1176 return 1, and the same comparison done with "<code>&gt;</code>" or
1177 "<code>&lt;</code>" should always return 0. (The epsilon value can be
1178 configured in the <code>fpconfig.hh</code> file.)
1179 Without epsilon this comparison probably returns the wrong value.
1180
1181 <p>The class supports these functions:
1182
1183 <p><table border=2>
1184 <tr>
1185  <td><code>abs(A)</code></td>
1186  <td>Absolute value of A. If A is negative, returns -A otherwise returns A.</td>
1187 </tr><tr>
1188   <td><code>acos(A)</code></td>
1189   <td>Arc-cosine of A. Returns the angle, measured in radians, whose cosine
1190       is A.</td>
1191 </tr><tr>
1192   <td><code>acosh(A)</code></td>
1193   <td>Same as acos() but for hyperbolic cosine.</td>
1194 </tr><tr>
1195   <td><code>asin(A)</code></td>
1196   <td>Arc-sine of A. Returns the angle, measured in radians, whose sine
1197       is A.</td>
1198 </tr><tr>
1199   <td><code>asinh(A)</code></td>
1200   <td>Same as asin() but for hyperbolic sine.</td>
1201 </tr><tr>
1202   <td><code>atan(A)</code></td>
1203   <td>Arc-tangent of (A). Returns the angle, measured in radians,
1204       whose tangent is (A).</td>
1205 </tr><tr>
1206   <td><code>atan2(A,B)</code></td>
1207   <td>Arc-tangent of A/B. The two main differences to atan() is
1208       that it will return the right angle depending on the signs of
1209       A and B (atan() can only return values betwen -pi/2 and pi/2),
1210       and that the return value of pi/2 and -pi/2 are possible.</td>
1211 </tr><tr>
1212   <td><code>atanh(A)</code></td>
1213   <td>Same as atan() but for hyperbolic tangent.</td>
1214 </tr><tr>
1215   <td><code>cbrt(A)</code></td>
1216   <td>Cube root of A. Returns the value whose cube is A.</td>
1217 </tr><tr>
1218   <td><code>ceil(A)</code></td>
1219   <td>Ceiling of A. Returns the smallest integer not smaller than A.
1220       Rounds up to the next higher integer. E.g. -2.9, -2.5 and -2.1 are
1221     rounded to -2.0, and 2.9, 2.5 and 2.1 are rounded to 3.0.</td>
1222 </tr><tr>
1223   <td><code>cos(A)</code></td>
1224   <td>Cosine of A. Returns the cosine of the angle A, where A is
1225       measured in radians.</td>
1226 </tr><tr>
1227   <td><code>cosh(A)</code></td>
1228   <td>Same as cos() but for hyperbolic cosine.</td>
1229 </tr><tr>
1230   <td><code>cot(A)</code></td>
1231   <td>Cotangent of A (equivalent to 1/tan(A)).</td>
1232 </tr><tr>
1233   <td><code>csc(A)</code></td>
1234   <td>Cosecant of A (equivalent to 1/sin(A)).</td>
1235 </tr><tr>
1236   <td><code>eval(...)</code></td>
1237   <td>This a recursive call to the function to be evaluated. The
1238       number of parameters must be the same as the number of parameters
1239       taken by the function. Must be called inside <code>if()</code> to avoid
1240       infinite recursion.</td>
1241 </tr><tr>
1242   <td><code>exp(A)</code></td>
1243   <td>Exponential of A. Returns the value of e raised to the power
1244       A where e is the base of the natural logarithm, i.e. the
1245       non-repeating value approximately equal to 2.71828182846.</td>
1246 </tr><tr>
1247   <td><code>floor(A)</code></td>
1248   <td>Floor of A. Returns the largest integer not greater than A. Rounds
1249       down to the next lower integer.
1250       E.g. -2.9, -2.5 and -2.1 are rounded to -3.0,
1251       and 2.9, 2.5 and 2.1 are rounded to 2.0.</td>
1252 </tr><tr>
1253   <td><code>if(A,B,C)</code></td>
1254   <td>If int(A) differs from 0, the return value of this function is B,
1255       else C. Only the parameter which needs to be evaluated is
1256       evaluated, the other parameter is skipped; this makes it safe to
1257       use <code>eval()</code> in them.</td>
1258 </tr><tr>
1259   <td><code>int(A)</code></td>
1260   <td>Rounds A to the closest integer. Equidistant values are rounded up.
1261     E.g. -2.9 is rounded to -3.0; -2.5 and -2.1 are rounded to -2.0,
1262     and 2.9 and 2.5 are rounded to 3.0; 2.1 is rounded to 2.0.</td>
1263 </tr><tr>
1264   <td><code>log(A)</code></td>
1265   <td>Natural (base e) logarithm of A.</td>
1266 </tr><tr>
1267   <td><code>log10(A)</code></td>
1268   <td>Base 10 logarithm of A.</td>
1269 </tr><tr>
1270   <td><code>max(A,B)</code></td>
1271   <td>If A&gt;B, the result is A, else B.</td>
1272 </tr><tr>
1273   <td><code>min(A,B)</code></td>
1274   <td>If A&lt;B, the result is A, else B.</td>
1275 </tr><tr>
1276   <td><code>pow(A,B)</code></td>
1277   <td>Exponentiation (A raised to the power B).</td>
1278 </tr><tr>
1279   <td><code>sec(A)</code></td>
1280   <td>Secant of A (equivalent to 1/cos(A)).</td>
1281 </tr><tr>
1282   <td><code>sin(A)</code></td>
1283   <td>Sine of A. Returns the sine of the angle A, where A is
1284       measured in radians.</td>
1285 </tr><tr>
1286   <td><code>sinh(A)</code></td>
1287   <td>Same as sin() but for hyperbolic sine.</td>
1288 </tr><tr>
1289   <td><code>sqrt(A)</code></td>
1290   <td>Square root of A. Returns the value whose square is A.</td>
1291 </tr><tr>
1292   <td><code>tan(A)</code></td>
1293   <td>Tangent of A. Returns the tangent of the angle A, where A
1294       is measured in radians.</td>
1295 </tr><tr>
1296   <td><code>tanh(A)</code></td>
1297   <td>Same as tan() but for hyperbolic tangent.</td>
1298 </tr><tr>
1299   <td><code>trunc(A)</code></td>
1300   <td>Truncated value of A. Returns an integer corresponding to the value
1301     of A without its fractional part.
1302     E.g. -2.9, -2.5 and -2.1 are rounded to -2.0,
1303     and 2.9, 2.5 and 2.1 are rounded to 2.0.</td>
1304 </tr>
1305 </table>
1306
1307 <p>(Note that for <code>FunctionParser_li</code> and
1308   <code>FunctionParser_gmpint</code> only the functions
1309   <code>abs()</code>, <code>eval()</code>, <code>if()</code>,
1310   <code>min()</code> and <code>max()</code> are supported.)
1311
1312 <p>Examples of function string understood by the class:
1313
1314 <p><code>"1+2"</code><br>
1315 <code>"x-1"</code><br>
1316 <code>"-sin(sqrt(x^2+y^2))"</code><br>
1317 <code>"sqrt(XCoord*XCoord + YCoord*YCoord)"</code><br>
1318
1319 <p>An example of a recursive function is the factorial function:
1320
1321 <code>"if(n>1, n*eval(n-1), 1)"</code>
1322
1323 <p>Note that a recursive call has some overhead, which makes it a bit slower
1324   than any other operation. It may be a good idea to avoid recursive functions
1325   in very time-critical applications. Recursion also takes some memory, so
1326   extremely deep recursions should be avoided (eg. millions of nested recursive
1327   calls).
1328
1329 <p>Also note that even though the maximum recursion level of
1330 <code>eval()</code> is limited, it is possible to write functions which
1331 never reach that level but still take enormous amounts of time to evaluate.
1332 This can sometimes be undesirable because it is prone to exploitation,
1333 which is why <code>eval()</code> is disabled by default. It can be enabled
1334 in the <code>fpconfig.hh</code> file.
1335
1336
1337 <!-- -------------------------------------------------------------------- -->
1338 <a name="inlinevars"></a>
1339 <h3>Inline variables</h3>
1340
1341 <p>The function syntax supports defining new variables inside the function
1342 string itself. This can be done with the following syntax:
1343
1344 <p><code>"&lt;variable name&gt; := &lt;expression&gt;; &lt;function&gt;"</code>
1345
1346 <p>For example:
1347
1348 <p><code>"length := sqrt(x*x+y*y); 2*length*sin(length)"</code>
1349
1350 <p>(Spaces around the '<code>:=</code>' operator are optional.)
1351
1352 <p>The obvious benefit of this is that if a long expression needs to be
1353 used in the function several times, this allows writing it only once and
1354 using a named variable from that point forward.
1355
1356 <p>The variable name must be an unused identifier (in other words, not an
1357 existing function, variable or unit name).
1358
1359 <p>The <code>&lt;function&gt;</code> part can have further inline variable
1360 definitions, and thus it's possible to have any amount of them, for example:
1361
1362 <p><code>"A := x^2; B := y^2; C := z^2; sqrt(A+B+C)"</code>
1363
1364 <p>The expressions in subsequent inline variable definitions can use any
1365 of the previous inline variables. It is also possible to redefine an inline
1366 variable. For example:
1367
1368 <p><code>"A := x^2; A := 2*A; sqrt(A)"</code>
1369
1370
1371 <!-- -------------------------------------------------------------------- -->
1372 <a name="whitespace"></a>
1373 <h3>Whitespace</h3>
1374
1375 <p>Arbitrary amounts of whitespace can optionally be included between
1376   elements in the function string.
1377   The following unicode characters are interpreted as whitespace:
1378 <table>
1379  <tr>
1380   <th>Character number</th>
1381   <th>Character name</th>
1382   <th>UTF-8 byte sequence</th>
1383  </tr>
1384  <tr><td>U+0009</td><td>HORIZONTAL TABULATION    </td><td>09</td></tr>
1385  <tr><td>U+000A</td><td>LINE FEED                </td><td>0A</td></tr>
1386  <tr><td>U+000B</td><td>VERTICAL TABULATION      </td><td>0B</td></tr>
1387  <tr><td>U+000D</td><td>CARRIAGE RETURN          </td><td>0D</td></tr>
1388  <tr><td>U+0020</td><td>SPACE                    </td><td>20</td></tr>
1389  <tr><td>U+00A0</td><td>NO-BREAK SPACE           </td><td>C2 A0</td></tr>
1390  <tr><td>U+2000</td><td>EN QUAD                  </td><td>E2 80 80</td></tr>
1391  <tr><td>U+2001</td><td>EM QUAD                  </td><td>E2 80 81</td></tr>
1392  <tr><td>U+2002</td><td>EN SPACE                 </td><td>E2 80 82</td></tr>
1393  <tr><td>U+2003</td><td>EM SPACE                 </td><td>E2 80 83</td></tr>
1394  <tr><td>U+2004</td><td>THREE-PER-EM SPACE       </td><td>E2 80 84</td></tr>
1395  <tr><td>U+2005</td><td>FOUR-PER-EM SPACE        </td><td>E2 80 85</td></tr>
1396  <tr><td>U+2006</td><td>SIX-PER-EM SPACE         </td><td>E2 80 86</td></tr>
1397  <tr><td>U+2007</td><td>FIGURE SPACE             </td><td>E2 80 87</td></tr>
1398  <tr><td>U+2008</td><td>PUNCTUATION SPACE        </td><td>E2 80 88</td></tr>
1399  <tr><td>U+2009</td><td>THIN SPACE               </td><td>E2 80 89</td></tr>
1400  <tr><td>U+200A</td><td>HAIR SPACE               </td><td>E2 80 8A</td></tr>
1401  <tr><td>U+200B</td><td>ZERO WIDTH SPACE         </td><td>E2 80 8B</td></tr>
1402  <tr><td>U+202F</td><td>NARROW NO-BREAK SPACE    </td><td>E2 80 AF</td></tr>
1403  <tr><td>U+205F</td><td>MEDIUM MATHEMATICAL SPACE</td><td>E2 81 9F</td></tr>
1404  <tr><td>U+3000</td><td>IDEOGRAPHIC SPACE        </td><td>E3 80 80</td></tr>
1405 </table>
1406
1407
1408 <!-- -------------------------------------------------------------------- -->
1409 <h2>Miscellaneous</h2>
1410
1411 <a name="evaluationchecks"></a>
1412 <h3>About evaluation-time checks</h3>
1413
1414 <p>By default <code>FunctionParser::Eval()</code> will perform certain sanity
1415 checks before performing certain operations. For example, before calling the
1416 <code>sqrt</code> function, it will check if the parameter is negative, and
1417 if so, it will set the proper error code instead of calling the function.
1418 These checks include:
1419
1420 <ul>
1421  <li>Division by (the exact value of) zero.
1422  <li>Square root of a negative value.
1423  <li>Logarithm of a non-positive value.
1424  <li>Arcsine or arccosine of a value not in the range [-1, 1]. (This includes
1425    hyperbolic versions of the functions.)
1426 </ul>
1427
1428 <p>However, the library <em>can not</em> guarantee that it will catch all
1429 possible floating point errors before performing them, because this is
1430 impossible to do with standard C++. For example, dividing a very large
1431 value by a value which is very close to zero, or calculating the logarithm
1432 of a very small value may overflow the result, as well as multiplying two
1433 very large values. Raising a negative number to a non-integral power may
1434 cause a <em>NaN</em> result, etc.
1435
1436 <p>As a rule of thumb, the library will (by default) detect invalid operations
1437 if they are invalid for a range of values. For example, square root is undefined
1438 for all negative values, and arc sine is undefined only values outside the range
1439 [-1, 1]. In general, operations which are invalid for only one single value
1440 (rather than a contiguous range of values) will not be detected (division by
1441 the exact value of zero is an exception to this rule) nor will
1442 overflow/underflow situations.
1443
1444 <p>The library cannot guarantee that floating point
1445 errors will never happen during evaluation. This can make the library to
1446 return the floating point values <em>inf</em> and <em>NaN</em>. Moreover,
1447 if floating point errors cause an interrupt in the target computer
1448 architecture and/or when using certain compiler settings, this library
1449 cannot guarantee that it will never happen.
1450
1451 <p>Since not all error situations can be caught, and since the sanity checks
1452 only slow down the evaluation (although only very slightly), the precompiler
1453 constant <code>FP_NO_EVALUATION_CHECKS</code> can be used to turn all the
1454 checks off. This might make the evaluation slightly faster in certain
1455 situations.
1456
1457 <p>Note that the optimizer never performs any sanity checks.
1458
1459
1460 <!-- -------------------------------------------------------------------- -->
1461 <a name="threadsafety"></a>
1462 <h3>About thread safety</h3>
1463
1464 <p>None of the member functions of the FunctionParser class are thread-safe.
1465 Most prominently, the <code>Eval()</code> function is not thread-safe.
1466 (In other words, the <code>Eval()</code> function of a single FunctionParser
1467 instance cannot be safely called simultaneously by two threads.)
1468
1469 <p>There are ways to use this library in a thread-safe way, though. If each
1470 thread uses its own FunctionParser instance, no problems will obviously
1471 happen. Note, however, that if these instances need to be a copy of a given
1472 FunctionParser instance (eg. one where the user has entered a function),
1473 a deep copy of this instance has to be performed for each thread. By
1474 default FunctionParser uses shallow-copying (copy-on-write), which means
1475 that a simple assignment of copy construction will not copy the data itself.
1476 To force a deep copy you can all the <code>ForceDeepCopy()</code> function on
1477 each of the instances of each thread after the assignment or copying has been
1478 done.
1479
1480 <p>Another possibility is to compile the FunctionParser library so that
1481 its <code>Eval()</code> function will be thread-safe. (This can be done by
1482 defining the <code>FP_USE_THREAD_SAFE_EVAL</code> or the
1483 <code>FP_USE_THREAD_SAFE_EVAL_WITH_ALLOCA</code>
1484 precompiler constant.) As long as only one thread calls the other functions
1485 of FunctionParser, the other threads can safely call the <code>Eval()</code>
1486 of this one instance.
1487
1488 <p>Note, however, that compiling the library like this can make
1489 <code>Eval()</code> slightly slower. (The <code>alloca</code> version, if
1490 supported by the compiler, will not be as slow.)
1491
1492 <p>Also note that the MPFR and GMP versions of the library cannot be
1493   made thread-safe, and thus this setting has no effect on them.
1494
1495
1496 <!-- -------------------------------------------------------------------- -->
1497 <a name="tipsandtricks"></a>
1498 <h3>Tips and tricks</h3>
1499
1500 <h4>Add constants automatically to all parser objects</h4>
1501
1502 <p>Often the same constants (such as <em>pi</em> and <em>e</em>) and other
1503 user-defined identifiers (such as units) are always used in all the
1504 <code>FunctionParser</code> objects throughout the program. It would be
1505 troublesome to always have to manually add these constants every time a
1506 new parser object is created.
1507
1508 <p>There is, however, a simple way to always add these user-defined identifiers
1509 to all instances. Write a class like this:
1510
1511 <pre>
1512     class ParserWithConsts: public FunctionParser
1513     {
1514      public:
1515         ParserWithConsts()
1516         {
1517             AddConstant("pi", 3.14159265358979323846);
1518             AddConstant("e", 2.71828182845904523536);
1519         }
1520     };
1521 </pre>
1522
1523 <p>Now instead of using <code>FunctionParser</code>, always use
1524 <code>ParserWithConsts</code>. It will behave identically except that the
1525 constants (and possibly other user-defined identifiers) will always be
1526 automatically defined. (Objects of this type even survive
1527 <a href="http://en.wikipedia.org/wiki/Object_slicing">slicing</a>, so
1528 they are completely safe to use anywhere.)
1529
1530
1531 <!-- -------------------------------------------------------------------- -->
1532 <a name="contact"></a>
1533 <h3>Contacting the author</h3>
1534
1535 <p>Any comments, bug reports, etc. should be sent to warp@iki.fi
1536
1537
1538 <!-- -------------------------------------------------------------------- -->
1539 <!--
1540 <a name="algorithm"></a>
1541 <h2>The algorithm used in the library</h2>
1542
1543 <p>The whole idea behind the algorithm is to convert the regular infix
1544 format (the regular syntax for mathematical operations in most languages,
1545 like C and the input of the library) to postfix format. The postfix format
1546 is also called stack arithmetic since an expression in postfix format
1547 can be evaluated using a stack and operating with the top of the stack.
1548
1549 <p>For example:
1550
1551 <p><table border=2>
1552 <tr><th>infix</th> <th>postfix</th></tr>
1553 <tr><td><code>2+3</code></td><td><code>2 3 +</code></td></tr>
1554 <tr><td><code>1+2+3</code></td><td><code>1 2 + 3 +</code></td></tr>
1555 <tr><td><code>5*2+8/2</code></td><td><code>5 2 * 8 2 / +</code></td></tr>
1556 <tr><td><code>(5+9)*3</code></td><td><code>5 9 + 3 *</code></td></tr>
1557 </table>
1558
1559 <p>The postfix notation should be read in this way:
1560
1561 <p>Let's take for example the expression: <code>5 2 * 8 2 / +</code>
1562 <ul>
1563  <li>Put 5 on the stack
1564  <li>Put 2 on the stack
1565  <li>Multiply the two values on the top of the stack and put the result on
1566     the stack (removing the two old values)
1567  <li>Put 8 on the stack
1568  <li>Put 2 on the stack
1569  <li>Divide the two values on the top of the stack
1570  <li>Add the two values on the top of the stack (which are in this case
1571     the result of 5*2 and 8/2, that is, 10 and 4).
1572 </ul>
1573
1574 <p>At the end there's only one value in the stack, and that value is the
1575 result of the expression.
1576
1577 <p>Why stack arithmetic?
1578
1579 <p>The last example above can give you a hint.
1580   In infix format operators have precedence and we have to use parentheses to
1581 group operations with lower precedence to be calculated before operations
1582 with higher precedence.
1583   This causes a problem when evaluating an infix expression, specially
1584 when converting it to byte code. For example in this kind of expression:
1585     <code>(x+1)/(y+2)</code>
1586 we have to calculate first the two additions before we can calculate the
1587 division. We have to also keep counting parentheses, since there can be
1588 a countless amount of nested parentheses. This usually means that you
1589 have to do some type of recursion.
1590
1591 <p>The simplest and mostefficient way of calculating this is to convert it
1592 to postfix notation.
1593   The postfix notation has the advantage that you can make all operations
1594 in a straightforward way. You just evaluate the expression from left to
1595 right, applying each operation directly and that's it. There are no
1596 parentheses to worry about. You don't need recursion anywhere.
1597   You have to keep a stack, of course, but that's extremely easily done.
1598 Also you just operate with the top of the stack, which makes it very easy.
1599 You never have to go deeper than 2 items in the stack.
1600   And even better: Evaluating an expression in postfix format is never
1601 slower than in infix format. All the contrary, in many cases it's a lot
1602 faster (eg. because all parentheses are optimized away).
1603   The above example could be expressed in postfix format:
1604     <code>x 1 + y 2 + /</code>
1605
1606 <p>The good thing about the postfix notation is also the fact that it can
1607 be extremely easily expressed in bytecode form.
1608   You only need a byte value for each operation, for each variable and
1609 to push a constant to the stack.
1610   Then you can interpret this bytecode straightforwardly. You just interpret
1611 it byte by byte, from the beginning to the end. You never have to go back,
1612 make loops or anything.
1613
1614 <p>This is what makes byte-coded stack arithmetic so fast.
1615 -->
1616
1617
1618 <!-- -------------------------------------------------------------------- -->
1619 <a name="license"></a>
1620 <h2>Usage license</h2>
1621
1622 <p>Copyright © 2003-2010 Juha Nieminen, Joel Yliluoma
1623
1624 <p>This Library is distributed under the
1625   <a href="http://www.gnu.org/copyleft/lesser.html">Lesser General Public
1626     License</a> (LGPL) version 3.
1627
1628 </body>
1629 </html>