TFunctionParser Automation Server

Contents

Introduction

What is TFunctionParser?

TFunctionParser™ is a parser for analyzing and evaluating mathematical functions.
The function term is a user given string like 'sin(x)*x'. The function term can be changed anytime.
TFunctionParser provides about 100 mathematical intrinsic functions and operations. The user can define functions, constants and variable names himself.

TFunctionParser was formerly a Delphi component, but with different Delphi versions the binaries were not compatible. Thus we had to compile the sources for each Delphi version (in some cases even the sources were not compatible). So we thought releasing a DLL that encapsulates TFunctionParser would be a good idea and we came to COM/Automation.

What is COM/Automation?

Here is Microsoft's Definition:

COM is a platform-independent, distributed, object-oriented system for creating binary software components that can interact. COM is the foundation technology for Microsoft's OLE (compound documents) and ActiveX (Internet-enabled components) technologies, as well as others.

Automation is a COM-based technology that allows developers to create custom applications to automate frequent tasks.

If this is your first contact with COM/Automation you might be a little confused - but you will soon get familiar with it.

Synthesis

Thus TFunctionParser is a software that can be used by software developers to build their own applications embedding a powerful and comprehensive mathematical parser for quick and easy analyzing and evaluating mathematical functions.

Every programming or scripting language that supports COM can use TFunctionParser: Delphi, C, C++, C#, PHP, Perl, VBScript, JavaScript, VBA, Java, PowerShell, ...

Features

TFunctionParser provides the following features:

Though floating point numbers are communicated with the automation client as double type (64 bit), TFunctionParser calculates internally with extended numbers (80 bit). This is because the floating point unit uses extended numbers, but Automation/COM supports only double as the most precise floating point data type.

System Requirements

Operation System: Any Windows system

TFunctionParser is available for 32 bit and 64 bit operating systems.

You need the variant which matches your client. That is, if you are running a 32 bit operating system, you will need TFunctionParser 32 bit.

If you are running a 64 bit operating system, things are a bit more complex. Usually (for clients like Windows Scripting Host) you need TFunctionParser 64 bit. But if your client is still a 32 bit application, you'll need the 32 bit variant. Please keep in mind to consider this also for the installation.

Information

TFunctionParser 7.4 is Shareware.
You may test it for a period of 30 days.
It may be copied and distributed unmodified (complete ZIP-file, no single files).

If you use it in your non-commercial applications you must register it. The license fee for non-commercial use is 20 EUR.
If you want to use TFunctionParser for commercial purposes please contact us.

Registered users of one of the former versions get a discount.

You will obtain a special edition without the automatic initial info screen. This special edition additionally contains a DLL interface.

If you are not a registered user, the infoscreen will appear each time an instance of TFunctionParser is created.
Unregistered use is limited to 30 days. Please note that unregistered use after this evalution period will violate copyright law and international treaties and you will make yourself liable to prosecution.

Contact:

eMail: mhgs@MHGSoft.de
URL: http://www.MHGSoft.de

You are obliged to quote our copyright in all your applications and programs.

When ordering your personal edition please confirm that you read this file and agree to the license conditions. Don't forget your eMail address.

If you find any bug, please don't hesitate to inform us. Details (functions, arguments, ...) would be helpful.
Any suggestions, questions, and comments are welcome.

----------------------------------
THE LEGAL DISCLAIMER
----------------------------------
THE INFORMATION AND CODE PROVIDED HEREUNDER (COLLECTIVELY REFERRED TO AS "SOFTWARE") IS 
PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT 
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 
IN NO EVENT SHALL MHGS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT,
INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF
MHGS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

Installation

The file MHGSPARS.ZIP contains the following files:

MHGSPARS.DLLServer-DLL
MHGSPARS.TXTshort ASCII formatted Info
FILE_ID.DIZdto.
PAD_FILE.XMLPortable Application Description file for software portals
README.HTMthis file
LOGOMHGS.GIFour logo
FAVICON.ICOTFunctionParser Icon
INSTALL.BATinstalls TFunctionParser (only Win2k/XP/2003/Vista/2008/7/8.x), see below
UNINSTAL.BATuninstalls TFunctionParser (only Win2k/XP/2003/Vista/2008/7/8.x), see below
FDEMO.DPR
FDEMO1.PAS
FDEMO1.DFM
providing a simple demo application for TFunctionParser (function plotter) under Delphi (subfolder "Delphi")
CALC.VBP
CALC.VBW
FORM1.FRM
FORM1.FRX
providing a simple demo application of TFunctionParser for Visual Basic (subfolder "VisualBasic")
CALC.HTAsimple demo as Hypertext Application with JavaScript (subfolder "Scripting")
CALC.VBSsample script for using Windows Script Host with VBScript (subfolder "Scripting")
CONST.PLsample script for Perl (subfolder "Scripting")
CALC.DOCsample macro for VBA under MS Word (subfolder "Office")
CALC.XLSsample macro for VBA under MS Excel (subfolder "Office")
CS_NET.ZIPZip archive containing a .NET sample written in C#

Examples for MSVC++ are available directly from us.

The essential file is MHGSPARS.DLL that contains TFunctionParser. It must be copied to your harddisk.

Windows requires the registration of COM/Automation-Servers in the Registry (which will require administrator privileges.).

This registration process can be done in different ways:

If you want to install the TFunctionParser 32 bit variant on a 64 bit operating system (to use it with 32 bit clients), you will need to install it to the 32 bit subsystem (install with e.g. c:\Windows\SysWOW64\regsvr32.exe).

Properties and Methods

Overview: Properties and Methods in alphabetical order:

AngleMode ErrorMessage Term
CleanUp FunctionsText Result
ConstantsText GetVarValue VarNamesText
DefineUserFunction SetVarValue Version
ErrorCode ShowInfo

Read/Write Properties

Term

Term is a character string (e.g. 'sin(x)') defining the given function.
Spaces are ignored. Lower or upper cases are not distinguished.
Arguments of functions must be in brackets.
Multiple arguments in functions must be separated by commata or semicola.

Syntax:
BSTR Term
AngleMode

Only relevant for trigonometric functions and their inverses (arc functions).
If TFunctionParser.Anglemode is RAD the unit for angles is radians (full angle =2*pi), if it is DEG the unit is degrees (full angle =360°), and if it is GON the unit is gons (full angle =400 gons).

Syntax:
TAngleMode AngleMode
TAnglemode=(RAD=0, DEG=1, GON=2)

VarNamesText

You can define variable names with VarNamesText. Default are x, y, z and t.
Each variable name must stand in a separat line (lines must be separated by CR LF (0xD,0xA)).
You may make comments in the same lines, after a '#'-sign (e.g. 'x #that is x');
If you use multiple TFunctionParser instances they will use the same variable names.

Syntax:
BSTR VarNamesText

ConstantsText

You can define an arbitrary number of constants with ConstantsText using the notation e.g. 'A1=1.5e-3'.
For TFunctionParser it is even possible to define constants like 'A2=sin(pi/4)' or 'A3=A2-A1'
Warning: The call of variable names (e.g. 'A4=exp(y)') will lead to wrong results. You must not call constants recursively (e.g. 'A5=sqr(A5+1)') or crosswise (e.g. 'A6=A7', 'A7=A6').
The constant identifiers must be unique. Otherwise the first one in the list is taken.
Reserved abbreviations for identifier are e, pi, C, TRUE and FALSE.
The sequence of the definition of the constants doesn't matter. You may even add your own comments in separat lines.
Lines must be separated by CR LF (0xD,0xA).
ConstantsText is automatically initialized with a list of physical constants. Read the property ConstantsText for obtaining the list. (cf. sample CONST.PL).
If you use multiple TFunctionParser instances they will use the same defined constants.

Syntax:
BSTR FunctionsText

FunctionsText

In this list you can define functions (macros) that are based on the intrinsic functions. For example: 'F(X;Y)=EXP(X)*COS(Y)'.
You must specify the arguments in brackets and separated by semicola on the left side. There must be at least one argument.
The programmer is responsible for correct syntax and unique identifiers.
Userdefined functions may depend on other userdefined funclions, like e.g. 'G(X)=SQR(F(X;PI))
Recursive or crosswise calls are not allowed.
Warning: If you use identifiers of predefined functions (e.g. SIN(X)) the latter ones are overwritten.
Your own comments may be included after a '#'-sign.
Lines must be separated by CR LF (0xD,0xA).
If you use multiple TFunctionParser instances they will use the same defined functions.
See CALC.VBS for a sample how to use the FunctionText property.

Syntax:
BSTR FunctionsText

Readonly Properties

Result

When you read the Result, the Term is evaluated and the function value returned.

Syntax:
double Result

ErrorCode

If an error occurs the ErrorCode is set according to the following list:

0everything is OK
1wrong parentheses / separators
2Syntax error / invalid term
3unknown identifier
4recursive function or constant
5wrong number of operands
6term is not analyzed
7function is not defined for argument(s)
8NaN: evaluation aborted
9declarations not assigned

You should check ErrorCode after assigning the term and after reading the result.

Syntax:
byte ErrorCode

ErrorMessage

The Errormessage gives you detailed verbose information on the errors that occured.

Syntax:
BSTR ErrorMessage

Version

Version indicates the used version.

Syntax:
BSTR Version

Methods

SetVarValue

You can define the variable value of any variable defined in the VarNamesText property.

Syntax:
VARIANT_BOOL SetVarValue(BSTR Name, double Value)
Parameters:
Name

the name of the variable.

Value

the numerical value of the variable.

Return value:
SetVarValue returns TRUE if the specified variable is defined, otherwise FALSE.
Predefined names for variables are x, y, z and t.

GetVarValue

GetVarValue returns the value of any variable that is defined in the VarNamesText property.

Syntax:
VARIANT_BOOL GetVarValue(BSTR Name, double Value)
Parameters:
Name

the name of the variable.

Value

the numerical value of the variable.

Return value:
GetVarValue returns TRUE if the specified variable is defined, otherwise FALSE.
Predefined names for variables are x, y, z and t.

DefineUserFunction

DefineUserFunction allows the definition of functions, which were written by yourself.

This feature is not available for scripting and programming languages which don't support function pointers.

Syntax:
VARIANT_BOOL DefineUserFunction(BSTR Name, unsigned long Address)
Parameters:
Name

the name of the function.

Value

the address of the function. The address of the function is given as an unsigned longword (32bit), which can be retrieved as the value of the function pointer. Please see remarks section below.

Return value:

DefineUserFunction returns TRUE if the function definition was accepted, otherwise FALSE.

Remarks

DefineUserFunction allows you to call a function whose code you wrote yourself.

Your function must be declared as

function myfunction(X:double):double
.
The stdcall calling convention is used to provide compatibility with as many automation clients as possible.

Then you can call

DefineUserFunction('MyFunctionName',DWORD(@myfunction))
.

Your function is accessed if you call 'MyFunctionName(x)' in the Term.

You can define multiple functions that way.

For undefining a previously defined function simply call

DefineUserFunction('MyFunctionName',nil)
.

ShowInfo

ShowInfo displays the about screen.

Syntax:
VARIANT_BOOL ShowInfo()
Return value:
ShowInfo always returns TRUE.

CleanUp

If you do not need TFunctionParser anymore and don't want to rely on garbage collection you can call CleanUp to free used resources. Warning: If you use TFunctionParser afterwards this can lead to an access violation.

Syntax:
void CleanUp()
Return value:
CleanUp doesn't return a value.

Recommended Use

Naming Conventions for Variables, Functions and Constants

The first character must be alphabetical. The remaining characters may be alphabetic or numerical. Special symbols are not supported (except underscore). Identifiers must be unique.

TFunctionParser Step by Step

For working with TFunctionParser you should perform the following steps:
Necessary steps are indicated by consecutive numbers. Letters mark optional steps that may be omitted if you don't want to use the respective features.

Please note that TFunctionParser must be installed on the respective computer.

(*1*) Create a TFunctionParser Object. The HowTo depends on your automation client. See the respective reference for more information.
(*A*)Define Variables using the VarNamesText property (optional).
(*B*)Define Constants using the ConstantsText property (optional).
(*C*)Define Functions using the FunctionsText property (optional).
(*D*)Define own functions with DefineUserFunction (optional, client must support function pointers).
(*E*)Change the AngleMode using the AngleMode property (optional).
(*2*) Set the Term property to the desired function term.
(*F*)Check the ErrorCode or ErrorMessage (optional).
(*3*) Set all required variable values using SetVarValue. If you don't use variables you can omit this step.
(*4*) Read the Result.
(*G*)Check the ErrorCode or ErrorMessage (optional).

Sample Programs

Attached to the MHGSPARS.ZIP file there are multiple sample scripts or programs.

Some of them are quite easy. They are only intented to demonstrate the general access on TFunctionParser in the respective language. If you have sufficient knowledge in the respective client language you should have no problems to modify and expand the listings for suiting your own wishes.

Some samples are a little more complex to show the capabilities of TFunctionParser.

The following Delphi listing shows the general use of TFunctionParser.
A simple calculator program may contain the following code. Clicking on a button will induce the program to read the function term and the variable value from the respective edit fields, evaluate these, and write the result as the caption of a label.

...
uses ComObj;
var FunctionParser:VARIANT;

procedure TForm1.FormCreate(Sender: TObject);
begin
   FunctionParser:=CreateOleObject('mhgspars.FunctionParser');     //(*1*)
end;

procedure TForm1.BitBtn1Click(Sender: TObject);
const xn:string='x';
begin
    FunctionParser.Term:=edit1.text;	                           //(*2*)
		{e.g. Term:='sin(x)/x'}
    FunctionParser.SetVarValue(xn,strtofloat(edit2.text));        //(*3*)
		{'x' must be defined as variable name} 
    label1.caption:='Result = '+floattostr(FunctionParser.Result); //(*4*)
    if FunctionParser.ErrorCode<>0 
         then label1.caption:=FunctionParser.ErrorMessage;         //(*F*)
   {It is indeed that easy to program a calculator}
end;
...

List of Operations and Functions

The separator between multiple arguments in functions is the semicolon (;). The decimal separator is the period (.).
Depending on your regional settings, the comma (,) may be used either as decimal or list separator.

The fourth column specifies the availability for TFunctionParser.

TFunctionParserTComplexParser
MHGSCompCalc
Adding:x + yadds x and yXX
Subtracting:x - ysubtracts y from xXX
Multiplying:x * ymultiplies x and yXX
fac(n)factorial of n, n!X
Dividing:x / ydivides x through yXX
n div m
n \ m
integer divisionX
rez(x)reciprocal value of xXX
n mod m
n % m
integer moduloX
modulo(x;y)rest of division x/yX
Powers:x ^ yx to the power of yXX
sqr(x)square of xXX
exp(x)exponential of xXX
Roots:sqrt(x)squareroot of xXX
cbrt(x)cubic root of xX
root(n;x)n-th root of xX
Logarithms:ln(x)log. with base e of xXX
lg(x)log. with base 10 of xX
lb(x)log. with base 2 of xX
log(b;x)common log. with base b of xX
Trigonometric Functions:sin(x)sine of xXX
cos(x)cosine of xXX
tan(x)tangent of xXX
cot(x)cotangent of xXX
sec(x)secans of xX
cosec(x)cosecans of xX
Arc Functions:arcsin(x) arc sine of xXX
arccos(x)arc cosine of xXX
arctan(x)arc tangent of xXX
atan2(y;x)arc tangent of y/xX
arccot(x)arc cotangent of xXX
Hyperbolic Functions:sinh(x)hyperbolic sine of xXX
cosh(x) hyperbolic cosine of xXX
tanh(x) hyperbolic tangent of xXX
coth(x) hyperbolic cotangent of xXX
Area Functions:arsinh(x)inverse hyperbolic sine of xXX
arcosh(x)inverse hyperboloc cosine of xXX
artanh(x)inverse hyperbolic tangent of xXX
arcoth(x)inverse hyperbolic cotangent of xXX
Statistical Function:gauss(x)normal distribution of xX
erf(x)error function of xX
inverf(x)inverse of error function of xX
n over k
bino(n;k)
binomial coefficient n over kX
poisson(μ;n)Poisson distribution of n with average μX
poicum(μ;n)cumulated Poisson distribution up to n with average μX
Random Numbers: rnd(x)random number in [0,x[X
rand(a;b)random number in [a,b[X
poirand(μ)Poisson distributed random numbers with average μX
gaussrand(μ;σ)Gaussian distributed random numbers with average μ and standard deviation σX
Bessel Functions:J0(x)0th order of xX
J1(x)1st order of xX
J2(x)2nd order of xX
J3(x)3rd order of xX
J4(x)4th order of xX
J5(x)5th order of xX
J(n;x)n-th order of xX
Integral Functions:Si(x)sine integral of xX
Ci(x)cosine integral of xX
Ei(x)exponential integral of xX
li(x)logarithm integral of xX
Gammafunction:gamma(x)gamma function of xX
Stepfunctions:theta(x)=1 if x >0, else =0X
sgn(x)signum function of xX
int(x)integer part of xX
round(x)x rounded to next integer valueX
ceil(x)x rounded to higher integer valueX
floor(x)x rounded to lower integer valueX
Periodical Functions:triangle(x)triangle waveform (period 2π)X
sawtooth(x)sawtooth waveform (period 2π)X
square(x)square waveform (period 2π)X
Absolute Values:abs(x)absolute |x|X(X)
cabs(x;y)absolute |x+iy|X
Miscellaneous:frac(x)non-integer part of xX
max(x;y)maximum value of x and yX
min(x;y)minimum value of x and yX
odd(n)=1 if n is odd, =0 if n is even X
gcd(n;m)greatest common divisor of n amd mX
lcm(n;m)least common multiple of n and mX
ramp(x;a;b)=0 if x<a, =1 if x>b, else continuation between a and bX
Bitwise and Logical Functions:a and b
a & b
bitwise logic ANDX
a or b
a | b
bitwise logic ORX
(a) xor (b)bitwise logic XORX
bnot(a)bitwise NOTX
not(a)
!a
logical NOTX
a shl b
a >> b
shifts a b bitpositions to the leftX
a shr b
a >> b
shifts a b bitpositions to the rightX
Relational Operators:x = y=1 if x is equal to y, else =0 X
x < > y
x != y
=1 if x is not equal to y, else =0 X
x < = y=1 if x is less or equal to y, else =0 X
x < y=1 if x is less than y, else =0 X
x > = y=1 if x is greater or equal to y, else =0 X
x > y=1 if x is greater than y, else =0 X
IF- Function:if(c;x;y)if condition c=1 then x, else if c=0 then yX
Properties of complex numbers: abs(z)absolute |z|(X)X
arg(z)argument (phase) of zX
re(z)real part of zX
im(z)imaginary part of zX
CC(z)
~z
complex conjugate of zX
Mathematical Constants:picircumference/diameter of circleXX
ebase of natural logarithmsXX
CEuler's constantXX
iimaginary unit, sqrt(-1)X
TRUElogical value 1.0X
FALSElogical value 0.0X
INFINITYsymbolical value for ∞X
NEGINFINITYsymbolical value for -∞X
NaNNot a Number (aborts evaluation)X
Number Formats: ninteger numbersXX
xfloating point numbersXX
zcomplex numbersX
$nhexadecimal numbersX

TFunctionParser was developed by MHGS.

last modified: 2018-05-11