TFunctionParser          
		  by Marianne H. Goeltl-Schuberth

TFunctionParser is a non-visual DELPHI component for evaluating mathematical functions. 
The function term is a user given string like 'sin(x)*x'. The function term can be
changed during runtime.
TFunctionParser provides more then 80 mathematical intrinsic functions and operations.
The user can define functions, constants and variable names himself.

Contents:
  1. Features 
  2. Information 
  3. Installation
  4. Properties, Methods, Events
  5. The Component TParserDeclarations
  6. Recommended Use 
  7. Sample programs
  8. List of operations and functions



1. Features 

	- Algebraic syntax, not case sensitive
	- Parentheses ()
	- Floating point numbers (extended)
        - Angles in radians, degrees or gons
	- Userdefined variablenames (default: x, y, z and t)
	- Implemented mathematical constants
	- Userdefined constants 
	- More then 80 predefined mathematical functions and operations in TFunctionParser
	- Userdefined functions based on the predefined ones (macros)
	  functions can be inserted into other functions (e.g. 'f(g(sin(1/x))+x/2)*h(g(x-1);pi)')	
	- Userfunctions: YOUR own code is evaluated
	- Easy to use: see 7. Sample programs 



2. Information

TFunctionParser V6.0 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 by 
sending 30 USD or 30 DM  (cash or Euro cheque / traveller's check) to the author.

If you want to use TFunctionParser for commercial purposes please contact me.

Registered users of one of the former versions get a discount.
You will obtain the registration code, that switches off the automatic initial info 
screen.
The registration code must not be passed on.

If you are not a registered user the infoscreen will appear each time an instance of 
TFunctionParser is created. Furthermore you can only run one instance per application. 
Unregistered use is limited to 30 days.


My address is:
			Marianne H. Goeltl-Schuberth	
			Egerlandstr. 18	
			D-91083 Baiersdorf	
			Germany

         eMail:		schuberth@t-online.de  
	 URL:		http://home.t-online.de/home/schuberth/
			(you can find the LATEST released version there)

When ordering your personal registration code please confirm that you read this file and 
agree to the license conditions. Quote the desired version. Don't forget your eMail or 
postal address. I would like to know where you obtained these components from.          

If you find any bug, please don't hesitate to inform me. 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 THE AUTHOR BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, 
INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF
THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 

	

3. Installation

The file FCTPRS3.ZIP (for Delphi 3), FCTPRS2.ZIP (for Delphi 2)  include the following files:

		FDEMO.DPR			providing a simple demo application
		FDEMO1.DFM			for TFunctionParser (function plotter)
		FDEMO1.PAS			

		FCTPRS3.DPK			source package (only in FCTPRS3.ZIP)
		FCTPARS.DCU			containing the components 
		FCTPARS.DCR                     	  TFunctionParser
		FCTPARS1.DCU				  and TParserDeclarations
		FCTPARS1.DFM
		FCTPARS2.DCU
		FCTPARS2.DFM
		FCTPARS5.DCU

		FCTPRS*.TXT 			short ASCII formatted Info, where * stands
						for the respective Delphi version
		FILE_ID.DIZ			dto.
		README.TXT			this file
  		NATCONST.DAT	        	selection of physical constants

For installing the components you need the files
					FCTPRS3.DPK  (only Delphi 3)
                                        FCTPARS.DCR
					FCTPARS.DCU
					FCTPARS1.DCU
					FCTPARS2.DCU
					FCTPARS5.DCU
					FCTPARS1.DFM
					FCTPARS2.DFM.

Attention: If you have already installed a former version of TFunctionParser you must remove
	   the respective DCU-files from your library and path first.

For Installation under Delphi 3:

- Choose from the menu File | Open
- Select the filter "Delphi Source Package (*.dpk)"
- Select FCTPRS3.DPK and click on Open
- Click on Install: The package is compiled first and then installed
- Confirm the information that new components have been installed by clicking on OK
- You find now on the palette, page MHGS:
	TFunctionParser and TParserDeclarations
- Close FCTPRS3.DPK.
  Make sure that the path to the library contains the directory with the DCUs.

For Installation under Delphi 2:

- Delphi 2: Choose from the menu Component | Install
- Choose Add
- Choose Browse
- Select the file format *.DCU
- Select FCTPARS.DCU
- Choose OK and wait while the compiler adds the new component to your library 
- You find now on the palette, page MHGS: 
	TFunctionParser and TParserDeclarations




4. Properties, Methods, Events

Input Properties

TFunctionParser.Declarations: TParserDeclarations
	TFunctionParser REQUIRES a TParserDeclarations component. Multiple 
	instances of TFunctionParser may share one TParserDeclarations instance.
	TParserDeclarations contains defaults and enables the use of self defined functions,
	constants and variable names.
	If you restrict on default settings there is no need to make changes to TParserDeclarations.
	Otherwise you should read 5. TParserDeclarations for more information.

TFunctionParser.Term : string			(only runtime)
	Term is a (huge) 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 semicola.

TFunctionParser.VarValues[name]: extended	(only runtime)
	The variable values are stored in the array VarValues. The name is the variable name like
	it must have been declared in TParserDeclarations.VarNames. See 5. TParserDeclarations.
	Defaults are x, y, z and t.

TFunctionParser.Anglemode : TAnglemode=(RAD, DEG, GON)	
	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).

TFunctionParser.About : boolean
	indicate whether the infoscreen is shown. 

TFunctionParser.Data : pointer
	You may add an arbitrary object or pointer to TFunctionParser. This is for your own use
	only. It doesn't interact with TFunctionParser itself. 


Output Properties:

TFunctionParser.Result : extended	(only runtime)
	When you read the Result, the Term is evaluated and the function value returned.

TFunctionParser.ErrorCode : byte 	(only runtime)
	If an error occurs the ErrorCode is set according to the following list:

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

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


TFunctionParser.Errormessage : string 
	The Errormessage gives you verbal information on the errors that occured.
	With a resource editor (e.g. Borland Resource Workshop) you can change the text of
	the errormessages in your executable program (only Delphi 3). 

TFunctionParser.Version : string
	indicates the used version.


Methods

TFunctionParser.ShowInfo
	If you want to see the infoscreen call ShowInfo.
	The minimum display time is 3 seconds. ShowInfo is AUTOMATICALLY executed when
	creating an instance of TFunctionParser if you are not registered.

TFunctionParser.DefineUserFunctions(AName: string; AUserFunction): boolean
	Userfunctions allow you to call a function whose code you wrote yourself. Your function
	must be declared as FUNCTION myfunction(X:EXTENDED):EXTENDED. Then you can call
	FUNCTIONPARSER.DEFINEUSERFUNCTIONS('MyFunctionName',myfunction).
	Your function is accessed if you call 'MyFunctionName(x)' in the Term. 
	You can define multiple functions that way. 
	The return value is TRUE if your definition was accepted.
	For undefining a previously defined function simply call 
		DefineUserFunctions('MyFunctionName',nil).
	A sample of DefineUserFunctions is given in FDEMO1.PAS or see 7. Sample Programs below..+          



Events

TFunctionParser.OnError
	The most common errors (syntax error, division by zero, ...) will raise the event OnError.
	


5. The Component TParserDeclarations

TParserDeclarations is a component that is required by TFunctionParser. It 
contains default settings and enables the definition of your own function macros, constants and
variable names.
Multiple instances of TFunctionParser may share one instance of TParserDeclarations.
You MUST assign the Declarations property of TFunctionParser to a TParserDeclarations instance.
There is no need to make any changes to TParserDeclarations if you restrict on the default settings.

Properties of TParserDeclarations:
 
TParserDeclarations.VarNames: TStringlist
	You can define variable names in this stringlist. Default are x, y, z and t.
	Each variable name must stand in a separat line.
	You may make comments in the same lines, after a '#'-sign (e.g. 'x	#that is x');

TParserDeclarations.Constants : TStringlist
	You can define an arbitrary number of constants in TParserDeclarations.Constants 
	using the notation e.g. 'A1=1.5e-3' (cf. examples in NATCONST.DAT). 
        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 may 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.

TParserDeclarations.Functions : TStringlist
	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.
	See also 7. Sample Programs
	
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.

TParserDeclarations.Data : pointer
	You may add an arbitrary object or pointer to TParserDeclarations. This is for
	your own use only. There is no influence on the behaviour of TParserDeclarations.

TParserDeclarations.ErrorMessage : string 	(only runtime)
	You can read the ErrorMessage for checking the correctness of the function macros
	and the variable names. Even if there are some invalid functions or variables, that will
	not necessarily affect the evaluations.



6. Recommended Use

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.

(*1*) 	You need an instance of TParserDeclarations. 
	Choose it from the palette, page MHGS, or create it at runtime.

(*2*)	You need an instance of TFunctionParser.
	Choose it from the palette, page MHGS, or create it at runtime.

(*3*)	Set the TFunctionParser.Declarations property to your TParserDeclarations instance. 
	That is the most important step ! At design time or runtime.
	
		Optional: (at design time or runtime)
		(*Aa*)	-Change TParserDeclarations.Functions 
		(*Ab*)	-Change TParserDeclarations.VarNames  
		(*Ac*)	-Change TParserDeclarations.Constants 
		(*B*)	-Change TFunctionParser.AngleMode
		(*C*)	-Define one or more user functions with TFunctionParser.DefineUserFunctions
			 (only runtime)

(*4*)	Set TFunctionParser.Term to the desired function term (only runtime)
		
		Optional: (only runtime)
		(*Da*)	-Check TParserDeclarations.ErrorMessage
		(*Db*)	-Check TFunctionParser.ErrorCode or ErrorMessage

(*5*)	Set all required variable values (only runtime)

(*6*)	Read T*Parser.Result (only runtime)

		Optional: (only runtime)
		(*Db*)	-Check TFunctionParser.ErrorCode or ErrorMessage




8. Sample Programs:

The following procedure 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. 

procedure TForm1.BitBtn1Click(Sender: TObject);
//(*1*) to (*3*) were done at design time 
begin
   with FunctionParser1 do begin
    Term:=edit1.text;					(*4*)
		{e.g. Term:='sin(x)/x'}
    VarValues['x']:=strtofloat(edit2.text);		(*5*)
		{'x' must be defined as variable name in ParserDeclarations1.VarNames} 
    label1.caption:='Result = '+floattostr(Result)	(*6*)
    if ErrorCode<>0 then label1.caption:=ErrorMessage;  (*Db*)
   end;
   {It is indeed that easy to program a calculator}
end;

---------

You can build compositions of userdefined functions.
Either define them at design time with the help of the object inspector or at runtime.
You can use any method of the TStrings object for this purpose. 
At design time you could have used the stringlist editor to include the following lines to
ParserDeclarations1.Functions:
	#(*Aa*)
	F1(X)=SIN(X)+F2(X)
	F2(X)=SIN(X)*X
	F3(X)=J(3;X)
	F4(X)=F1(X)+F3(X)
	G(a;b;x)=IF((a<x)and(x<b);x;0) #=x if x is between a and b 
	H(beta)=g(f1(beta);f3(beta);beta-pi)	# senseless sample

The following code demonstrates how to define a user function (*C*) and adds constants (*Ac*).

function twice(x:extended):extended; {sample user function}
begin
 result:=2*x;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
   FunctionParser1.DefineUserFunctions('TWICE',twice);        (*C*)
   FunctionParser1.Term:='twice(exp(x/5))+odd(round(x))'; (*4*) {Term is initialized here}
   ParserDeclarations1.Constants.loadfromfile('Natconst.dat'); (*Ac*)
               { includes physical constants}
end;


8. List of Operations and Functions

The separator between multiple arguments in functions is the semicolon (;). 
This character was choosen because the comma (,) is used as decimal separator 
in some countries.
Some Operators require their arguments in parentheses.
The second column specifies the availability for TFunctionParser / TDBParser (f) or 
TComplexParser (c). 

Adding:			fc	x + y   	adds x and y
Subtracting:		fc	x - y   	subtract y from x
Multiplying:		fc	x * y		multiplies x and y
			f 	fac(n)		factorial of n, n!	
Dividing:		fc	x / y		divides x through y
			f	(n) div (m)	integer division
			fc	rez(x) 		reciprocal value of x
			f	(n) mod (m)	integer modulo
			f	modulo(x;y)	rest of division x/y
Powers:			f	x ^ y		x to the power of y
			fc	sqr(x) 		square of x
			fc	exp(x) 		exponential of x
Roots:			fc	sqrt(x)		squareroot of x
			f	cbrt(x) 	cubic root of x
			f 	root(n;x)	n-th root of x
Logarithms:		fc	ln(x)		log. with base e of x
			f	lg(x)		log. with base 10 of x
			f	lb(x)		log. with base 2 of x
			f 	log(b;x)	common log. with base b of x
Trigonometric Functions:fc	sin(x)		sine of x
			fc	cos(x)		cosine of x
			fc	tan(x)		tangent of x
			fc	cot(x)		cotangent of x
Arc Functions:		fc	arcsin(x)	arc sine of x
			fc	arccos(x)	arc cosine of x
			fc	arctan(x)	arc tangent of x
			f 	atan2(y;x)	arc tangent of y/x
			fc	arccot(x)	arc cotangent of x
Hyperbolic Functions:	fc	sinh(x)		hyperbolic sine of x
			fc	cosh(x)		hyperbolic cosine of x
			fc	tanh(x)		hyperbolic tangent of x
			fc	coth(x)		hyperbolic cotangent of x
Area Functions:		fc	arsinh(x)	inverse hyperbolic sine of x
			fc	arcosh(x)	inverse hyperboloc cosine of x
			fc	artanh(x)	inverse hyperbolic tangent of x
			fc	arcoth(x)	inverse hyperbolic cotangent of x
Statistical Function:	f	gauss(x)	normal distribution of x
			f	erf(x)		error function of x
			f	inverf(x)	inverse of error function of x
			f	(n) over (k)	binomial coefficient n over k
			f 	bino(n;k)	binomial coefficient n over k
			f 	poisson(mu;n)	poisson distribution of n with average mu
			f	poicum(mu;n)	cumulated poison distribution up to n (ave. mu)
Random Numbers:		f	rnd(x)		random number in [0,x[ 
			f 	rand(x;y)	random number in [x,y[
			f	poirand(mu)	Poisson distributed random numbers (ave. mu) 
Bessel Functions:	f	J0(x)		0th order of x
			f	J1(x)		1st order of x
			f	J2(x)		2nd order of x
			f	J3(x)		3rd order of x
			f	J4(x)		4th order of x
			f	J5(x)		5th order of x
			f 	J(n;x)		n-th order of x
Integral Functions:	f	Si(x)		sine integral of x 
			f	Ci(x)		cosine integral of x
			f	Ei(x)		exponential integral of x
			f	li(x)		logarithm integral of x
Gammafunction:		f	gamma(x)	gamma function of x
Stepfunctions:		f	theta(x)	=1 if x>0, else =0
			f	sgn(x)		signum function of x
			f	int(x)	        integer part of x
			f	round(x)	x rounded to next integer value
			f	ceil(x)		x rounded to higher integer value
			f	floor(x)	x rounded to lower integer value
Absolute Values:	f	abs(x)		absolute |x|
			f 	cabs(x;y)	absolute |x+iy|
Miscellaneous:		f	frac(x)		non-integer part of x
			f 	max(x;y)	maximum value of x and y
			f 	min(x;y)	minimum value of x and y	
			f	odd(n)		=1 if n is odd, =0 if n is even
Bitwise and Logical	f	(a) and (b)	bitwise logic AND
	Functions:	f	(a) or (b)	bitwise logic OR
			f	(a) xor (b)	bitwise logic XOR
			f	bnot(a)		bitwise NOT
			f	not(a)		logical NOT
			f	(a) shl (b)	shifts a b bitpositions to the left
			f	a << b		dto.
			f	(a) shr (b)	shifts a b bitpositions to the right	
			f	a >> b		dto.
Relational Operators:	f	x = y		=1 if x is equal to y, else =0
			f	x <> y		=1 if x is not equal to y, else =0
			f	x <= y		=1 if x is less or equal to y, else =0
			f	x < y		=1 if x is less than y, else =0
			f	x >= y		=1 if x is greater or equal to y, else =0
			f	x > y		=1 if x is greater than y, else =0
Properties of complex	c	abs(z)		absolute |z|
	numbers:	c	arg(z)		argument (phase) of z
			c	re(z)		real part of z
			c	im(z)		imaginary part of z
			c	CC(z)		complex conjugate of z
			c	~z		complex conjugate of z
IF- Function:		f	if(c;x;y)	if condition c=1 then x, else if c=0 then y
User Function:		fc	userfct(x)	user implemented function
Mathematical Constants:	fc	pi		circumference/diameter of circle
			fc	e		base of natural logarithms
			fc	C		Euler's constant
			f	TRUE		logical value 1.0
			f	FALSE		logical value 0.0
                        c	i		imaginary unit, sqrt(-1)        
			f	NaN		not a number (aborts evaluation)


	Marianne H. Goeltl-Schuberth                                 