Delphi/Kylix Math Functions

General Math Functions


Contents

A. Arithmetic Functions
B. Logarithm/Exponential Functions
C. Trigonometric Functions
D. Conversions and Formatting
E. Financial Functions
F. Sorting, Discrete Mathematics
G. Miscellenaous
H. Sources Key

A. Arithmetic Functions
Note:  min, max, sum, average, etc. functions are in the Statistics Section

Function Name Description Source(s)
abs Function Abs(X);
X is an integer-type or real-type expression.
system
ceil
ceiling
Function Ceil(X: Extended):Integer;
rounds up: smallest integer >= X, |X| < MaxInt
math
Clipper, AugMath
CompMod floating point "Comp" modulus ESBMaths
Cube x3 AugMath
Cubic Optimized code for cubic equation
www.optimalcode.com/excubic.zip 
 
Dec Procedure Dec(var X [ ; N: Longint ] );
X is a variable of an ordinal type (including Int64 in D4). Dec(X) corresponds to the statement X := X - 1, and Dec(X, N) corresponds to the statement X := X - N.
system
DecLim, DecLimSI, DecLimW, DecLimI, DecLimL Decrements type to a limit.  Below limit no decrement occurs. ESBMaths
Distance Finding the distance between two TPoints. Also, see hypot below. MathX, ESBMaths
div x div y, integer division operator, implemented as Delphi native operator  
DivMod procedure DivMod(Dividend: Integer; Divisor: Word;
                 var Result, Remainder: Word);

Also see:  MulDiv

SysUtils (D3)
ESBMagnitude returns magnitute of given value ESBMaths
Exponent   AugMath
ExtMod, ExtRem floating point modulus, remainder ESBMaths
Fibonacci sequence Compute the N-th value in the Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13, 21, ...) directly by solving the recurrence relation. This is explained in math books or perhaps analysis of algorithms books.

u(N) = [ (0.5 + 0.5*SQRT(5))N - (0.5 - 0.5 * SQRT(5))N ] / SQRT(5)

where u(N) is the Nth term in the sequence and SQRT(5) = square root of 5.

 
fix   MathX
FloatIsNegative
FloatIsPositive
FloatIsZero
Compares if value is within specified tolerance of zero ESBMaths
floor Function Floor(X: Extended): Integer;
rounds down: largest integer <= X, |X| < MaxInt
math, Clipper. MathX, AugMath
fmod x mod y mathlib2(math387)
frac Function Frac(X: Real): Real;
Frac(X) = X - Int(X)
Fractional part of the floating-point argument
system
frexp Procedure Frexp(X: Extended; var Mantissa: Extended; var Exponent: Integer) register;

separates the mantissa and exponent
math, MathX
gcd greatest common divisor

Euclid's method to determine the greatest common divisor of two integers.  
Recursive solution.

AugMath,
ESBMaths
Hi Function Hi(X): Byte;
The Hi function returns the high-order byte of X as an unsigned value. X is an expression of type Integer or Word.
System
hypot,
EuclideanNorm,
Pythag,
Distance
Function Hypot(X, Y: Extended): Extended;

SQRT(x2 + y2)
Distance from (0,0) to (x,y). Also see norm.
math, EZmath, TPmath1(fmath), ESBMaths, MathX, AugMath
Inc Procedure Inc(var X [ ; N: Longint ] );
X is a variable of an ordinal type (including Int64 in D4). Inc(X) corresponds to the statement X := X + 1, and Inc(X, N) corresponds to the statement X := X + N.
system
IncLim, IncLimSI, IncLimW, IncLimI, IncLimL Increments type to a limit.  Above limit no increment occurs. ESBMaths
int Function Int(X: Real): Real;
Int(x) = x rounded toward zero
Integer part of the floating-point argument. See also trunc.

Delphi in a NutShell, p. 241

system
IsEqual Tests to see if two doubles are effectively equal. Floating point numbers are never exact, so we need an approximation.   (efg:  not very general?) Calvert
IsNumeric Function IsNumeric(s: String) : Boolean;
  VAR
    Code: Integer;
    Value: Double;
BEGIN
  val(s, Value, Code);
  Result := (Code = 0)
END;
 
IsPositiveArray TRUE if all elements > Tolerance value ESBMaths
ISqrt Integer SQRT ESBMaths
iSwap swap 2 integer TPmath1(fmath)
lcd least common denominator (Euclid's algorithm) <find source for this>
lcm least common multiple ESBMaths
Lo Function Lo(X): Byte;
The Lo function returns the low-order byte of X as an unsigned value. X is an expression of type Integer.
System
MakeWord Function MakeWord(A, B: Byte): Word; RxLib
Max, Min   see Statistics Functions
Mean, StdDev   see Statistics Functions
mod x mod y, modulo or remainder operator.
Just like x DIV y gives the integer quotient, x MOD y gives the remainder from the division. Example: 25 MOD 9 = 7
 
MulDiv Function MulDiv(nNumber, nNumerator, nDenominator: Integer): Integer;

Example: MulDiv(value, 27, 100) = 27% of value

MulDiv rounds the result. For example, MulDiv(57, 255, 217) = 67, since 57*255/217 = 66.98.

Also see:  DivMod

Delphi Windows unit (D3)
norm Function Norm(const Data: array of Double): Extended;
Square root of the sum of squares.
Euclidean L2 norm: SQRT(SumOfSquares).
Example: norm([1, 3, 5]) = SQRT(12 + 32 + 52)
use "slice" with open array parameter
math,
EZmath
odd Function Odd(X: LongInt): Boolean; system
pi Function Pi: Extended; system
poly Function Poly(X: Extended; const Coefficients: array of Double): Extended;

Example: Poly(x, [ 1.0, -2.0, 1.0]) = x2 - 2x + 1. Polynomial evaluation with Horner's method. Use "slice" open array parameter for variable-sized polynomial

math, MathX
poly Evaluate polynomial TPmath1 (polynom)
RelativePrime determine if tow integers are relatively prime to each other ESBMaths
RFrac Evaluates rational fraction TPmath1 (polynom)
RootPol3 Real roots of polynomial up to degree 3 TPmath1 (polynom)
round Function Round(X: Extended): LongInt; (D1-D3)
Function Round(X: Extended): Int64; (D4)

Round(x) rounds to nearest integer, or in the case of a tie then to the nearest even integer. Examples: Round(2.5) = 2, Round(+3.499999) = 3, and Round(3.5) = 4.  [Thanks to John Herbster for clarifying this explanation.]

Ray Lischner has functions GetRoundMode and SetRoundMode to control rounding in his math10.zip.

Delphi in a NutShell, p. 324

Note:  Trunc is slower than Round.  According to John Herbster in a newsgroup posting:  Trunc has to save the FPU control word and change it twice.  Round does not. 

system
SameFloat Compares if floats are within specified tolerance

(the initial tolerance value is ESBTolerance:  Extended = 5.0E-324;  // MinDouble)

ESBMaths
sgn sign TPmath1(fmath)
Sgn, Sign sign ESBMaths, AugMath
slice Function Slice(var A: array; Count: Integer): array;
Slice returns a sub-section (a "slice") of an array passed as an open array parameter. This allows dynamically allocated arrays to be passed as open array parameters.
system
sqr Function Sqr(X: Extended): Extended;
squared: sqr(x) = x2

Delphi uses "compiler magic" so this "function" does not incur the normal overhead of a function call.

system
sqrt Function Sqrt(X: Extended): Extended;
square root: sqrt(x) = x0.5
system
Sum   see Statistics Functions
swap Function Swap(X);
Swap exchanges the high- and low-order bytes within a Word.
Provided for backwards compatibility only.
system
Swap Swap two reals TPmath1(fmath)
SwapInt, SwapInt64, SwapLong Procedure SwapInt(Var Int1, Int2: Integer);
Procedure SwapInt64(Var Int1, Int2: Int64);
Procedure SwapLong (Var Int1, Int2: LongInt);
RxLib
SwapB, SwapSI, SwapW, SwapI, SwapL, SwapI32, SwapC, SwapInt64,
SwapExt,
SwapDbl,
SwapSing
Swap two values ESBMaths
Swap32c Swap bytes with 4-byt integer
Robert Lee's UseNet Post
 
trunc Function Trunc(X: Extended): LongInt; (D1-D3)
Function Trunc(X: Extended): Int64; (D4)

Trunc(x) = x rounded toward zero
Integer part of the floating-point argument. See also int.

Delphi in a NutShell, p. 380

Note:  Trunc is slower than Round.  According to John Herbster in a newsgroup posting:  Trunc has to save the FPU control word and change it twice.  Round does not. 

system

B. Logarithm/Exponential Functions
www.math.utep.edu/sosmath/algebra/logs/log1/log1.html
www.sisweb.com/math/algebra/exponents.htm

Function Name Description Source(s)
ESBLog10, ESBLog2, ESBLogBase ESB Extended Log functions ESBMaths
exp Function Exp(X: Real): Real;
exp(x) = ex

Robert Lee's "fast" routines, dexp and fexp, in UseNet Post

system, TPmath1(fmath)
exp2 exp2(x) = 2x TPmath1(fmath)
exp10 exp10(x) = 10x TPmath1(fmath)
ExpFixed   Stockton
ExpFloat   Stockton
fexp ex mathlib2(math387)
flog, fln log10, loge mathlib2(math387)
ften_to 10x mathlib2(math387)
fy_to_x yx mathlib2(math387)
ILog2 integer part of the base-2 logarithm of integer ESBMaths
IntPow, ESBIntPower float to non-negative integer power ESBMaths
IntPower Function IntPower(Base: Extended; Exponent: Integer): Extended register;

xn, Raise base to an integral power.

math, TPmath1(fmath), MathX
ldexp Function Ldexp(X: Extended; P: Integer): Extended register;

x * 2P

math, MathX
ln Function Ln(X: Real): Real;
natural (basee) log

Robert Lee's "fast" routines, dln and fln, in UseNet Post

How can I compute a base-a logarithm, that is, loga x?

logn x = logb x / logb n = (logb x)(logn b)

log10 x = loge x / loge 10 = (loge x)(log10 e) = 0.4342944819 loge x

loge x = log10 x / log10 e = (log10 x)(loge 10) = 2.3025850930 log10 x

inline, TPmath1(fmath)
lnxp1 Function LnXP1(X: Extended): Extended;
Ln(x + 1) is accurate for x near zero
math, MathX
log base-a log EZmath, AugMath
log2 Function Log2(X: Extended): Extended;
base-2 log
math, TPmath1 (fmath), MathX
log10 Function Log10(X: Extended): Extended;
base-10 log
math, EZmath, TPmath1 (fmath), MathX
logN Function LogN(Base, X: Extended): Extended;
base-N log
math, MathX, AugMath
LogXtoBaseY Base-Y Logarithm of X ESBMaths
logxy Log of X to base Y Calvert
NthRoot   AugMath
pow(x, y) xy = exp(y * ln(x)) TPmath1 (fmath)
pow2(x) 2^x ESBMaths
power(x, y) Function Power(Base, Exponent: Extended): Extended;
xy = exp(y * ln(x))
Raise Base to any power, Base > 0
math, EZmath,
MathX, Stockton, Calvert, Turbo (p. 141), AugMath
power10 powers of 10 MathX
RPower real number to a real power Turbo (p. 141)
TenToY 10^Y ESBMaths
TwoToY 2^Y ESBMaths
XtotheY Raise X to the Y Power Calvert
XtoY X to the Y Power ESBMaths

C. Trigonometric Functions
www.math.utep.edu/sosmath/trig/trig.html
www.sisweb.com/math/trig/identities.htm

See Engineering Math Functions page  for Hyperbolic Trig Functions

Function Name Description Source(s)
Angle Conversions Cycle, radian, grad, degree

function CycleToDeg(const Cycles: Float): Float;
function CycleToGrad(const Cycles: Float): Float;
function CycleToRad(const Cycles: Float): Float;
function DegToCycle(const Degrees: Float): Float;
function DegToGrad(const Degrees: Float): Float;
function DegToRad(const Degrees: Float): Float;
function GradToCycle(const Grads: Float): Float;
function GradToDeg(const Grads: Float): Float;
function GradToRad(const Grads: Float): Float;
function RadToCycle(const Radians: Float): Float;
function RadToDeg(const Radians: Float): Float;
function RadToGrad(const Radians: Float): Float;

JCLUnitConv
arccos Function ArcCos(X: Extended): Extended;
arccos(x) = PI/2 - arctan(x / sqrt(1-sqr(x)))
Input: |X| <= 1, Output: [0 .. PI]
math, EZmath, TPmath1(fmath), Stockton(invcos), MathX, Calvert, Turbo (p. 141), AugMath
arccos2 Dr. John Stockton's UseNet Post using ArcTan2  
arccot arccot(x)

Function ArcCot(const X: Extended): Extended; 

Kylix math,
EZmath, Stockton(arccot)
arccsc arccsc(x)
Output: [0 .. PI/2) union [-PI .. -PI/2)

Function ArcCsc(const X: Extended): Extended; 

Kylix math, EZmath
arcsec arcsec(x)
Output: [0 .. PI/2) union [PI .. 3*PI/2)

Function ArcSec(const X: Extended): Extended; 

Kylix math, EZmath
arcsin arcsin(x) = arctan(x / sqrt(1-sqr(x)))
Input: |X| <= 1, Output: [-PI/2 .. PI/2]

Function ArcSin(X: Extended): Extended;

math, EZmath, TPmath1(fmath), Stockton(invcos), MathX, Calvert, Turbo (p. 141), AugMath
arcsin2 Dr. John Stockton's UseNet Post using ArcTan2  
arctan Function ArcTan(X: Extended): Extended;
Input: x <> 0, Output: -PI/2 .. PI/2
angle the ray (0,0) to (x,y) makes with positive X-axis

Use arctan2 to get angles in all four quadrants.

Tips and Tricks from Delphi in a NutShell, p. 137:

  • Integers and Variant arguments are automatically converted to floating-point.
    To convert an Int64 argument, add 0.0.
  • If X is positive infinity (INF), the result is an approximation to PI/2; if X is negative infinity (-INF), the result is an approximation of -PI/2.
  • If X is a quiet NaN, the result is X.
  • IF X is a signaling NaN, Arctan reports EInvalidOp.
system, TPmath1(fmath), Stockton(invcos)
arctan2 Function ArcTan2(Y, X: Extended): Extended;
ArcTan2 calculates ArcTan(Y/X), and returns an angle in the correct quadrant. Input: |Y| < 2^64, |X| < 2^64, X <> 0 Output: [-PI..PI]

Example:
// Given points(iText,jText) and (iTarget,jTarget). The 
// angle between the x-axis and the vector (iTarget-iText,
// jTarget-jText) ranges in the open interval [0.0, 360.0)
// degrees.  (0 degrees is the +X axis).
//  Note: Normally, ArcTan2 returns a value from -PI to PI.
angle := 180 * (1 + ArcTan2(jText-jTarget, iTarget-iText) / PI);
IF   angle >= 360.0
THEN angle := angle - 360.0;

math, EZmath,
Stockton(fpatan2), TPmath1(fmath),
MathX
bearing   MathX
Coordinate Conversions Cartesian, polar

procedure CartesianToPolar(const X, Y: Float; var R, Phi: Float);

procedure PolarToCartesian(const R, Phi: Float; var X, Y: Float);

procedure CartesianToCylinder(const X, Y, Z: Float; var R, Phi, Zeta: Float);

procedure CartesianToSpheric(const X, Y, Z: Float; var Rho, Theta, Phi: Float);

procedure CylinderToCartesian(const R, Phi, Zeta: Float; var X, Y, Z: Float);

procedure SphericToCartesian(const Rho, Theta, Phi: Float; var X, Y, Z: Float);

JCLUnitConv
cos Function cos(X: Extended): Extended;

The value x must be in radians.  To convert from degrees to radians use DegToRad.  For example, cos(60 degrees) in Delphi would be cos(DegToRad(60)) = 0.5.

FASTEST Sin, Cos, Tan and CTan functions. 
http://delphi.icm.edu.pl/ftp/d30free/sincosx.zip

Tips and Tricks from Delphi in a NutShell, p. 172:

  • Integers and Variant arguments are automatically converted to floating-point.
    To convert an Int64 argument, add 0.0.
  • If X is a quiet NaN, the result is X.
  • IF X is a signaling NaN, cos reports EInvalidOp.
system, TPmath1(fmath)
Cosecant also see csc

Function Cosecant(const X: Extended): Extended; 

Kylix math, 
AugMath
cot cot(x) = 1/tan(x), with x <> 0

function Cot(const X: Extended): Extended; 

simply calls cotan

Kylix math, EZmath
cotan Function Cotan(X: Extended): Extended; math, MathX
CoTangent also see cotan AugMath
csc csc(x) = 1/sin(x)

Function Csc(const X: Extended): Extended; 

simply calls Cosecant

Kylix math
CycleToDeg Radians := Cycles * 2PI

Function CycleToDeg(const Cycles: Extended): Extended;

Kylix math
CycleToGrad Function CycleToGrad(const Cycles: Extended): Extended;  Kylix math
CycleToRad Function CycleToRad(Cycles: Extended): Extended;
Cycles to Radians.
Radians = Cycles * 2 * PI
math, MathX
DegToCycle Function DegToCycle(const Degrees: Extended): Extended;  Kylix math
DegToGrad Function DegToGrad(const Degrees: Extended): Extended; Kylix math
DegToRad Function DegToRad(Degrees: Extended): Extended;
Degrees to Radians

Radians = Degrees * PI / 180

math, MathX, AugMath
DMS2Extended, Extended2DMS Converts degrees, minutes, seconds to an extended real, or vice versa ESBMaths
ESBCosec, ESBCot, ESBSec, ESBTan

ESBArcCosec, ESBArcCos, ESBArcSin, ESBArcSec

trig and inverse trig functions ESBMaths
ESBSinCos compute SIN and COS in a single call ESBMaths
farccos, farcsin, farctan, farctan2   mathlib2(math387)
fcos, fsin, ftan   mathlib2(math387)
FindX, FindY   MathX
FixAngle set angle in [-PI .. PI] TPmath1(fmath)
fmod_2PI x mod (2*PI) mathlib2(math387)
GradToCycle Function GradToCycle(const Grads: Extended): Extended;  Kylix math
GradToDeg Function GradToDeg(const Grads: Extended): Extended;  Kylix math
GradToRad Function GradToRad(Grads: Extended): Extended;
Grads to Radians.
Radians = Grads * PI / 200
math, MathX
nspSDegToRad, nspDDegToRad Degrees to radians ISPL
PolarToRect   MathX
Polar2XY, XY2Polar Convert polar coordinates to cartesian coordiantes, or vice versa ESBMaths
RadToCycle Function RadToCycle(Radians: Extended): Extended;
Radians to cycles.
Cycles = Radians / (2 * PI)
math, MathX
RadToDeg Function RadToDeg(Radians: Extended): Extended;
Radians to degrees.
Degreees = Radians * 180 / PI
math, MathX, AugMath
RadToGrad Function RadToGrad(Radians: Extended): Extended;
Radians to grads.
Grads = Radians * 200 / PI
math, MathX
RectToPolar   MathX
sec sec(x) = 1/cos(x)

Function Sec(const X: Extended): Extended; 

Simply calls Secant.

Kylix math
Secant see sec

Function Secant(const X: Extended): Extended;

Kylix math, AugMath
sin Function Sin(X: Extended): Extended;

The value x must be in radians.  To convert from degrees to radians use DegToRad.  For example, sin(30 degrees) in Delphi would be sin(DegToRad(30))= 0.5.

FASTEST Sin, Cos, Tan and CTan functions. 
http://delphi.icm.edu.pl/ftp/d30free/sincosx.zip

Tips and Tricks from Delphi in a NutShell, p. 341-342:

  • Integers and Variant arguments are automatically converted to floating-point.
    To convert an Int64 argument, add 0.0.
  • If X is a quiet NaN, the result is X.
  • IF X is a signaling NaN, sin reports EInvalidOp.

John Herbster's UseNet Post about since function for large numbers, such as sin(1e18)

system, TPmath1 (fmath)
sincos Procedure SinCos(Theta: Extended; var Sin, Cos: Extended) register;

sin(theta) and cos(theta): SinCos is 2x faster than calling Sin and Cos separately for the same angle
math, mathlib2(math387), Stockton(fsincos), MathX
SphericalToRect   MathX
tan Function Tan(X: Extended): Extended;

The value x must be in radians.  To convert from degrees to radians use DegToRad.  For example, tan(45 degrees) in Delphi would be tan(DegToRad(45)) = 1.0.

tan(x) = sin(x)/cos(x)

FASTEST Sin, Cos, Tan and CTan functions. 
http://delphi.icm.edu.pl/ftp/d30free/sincosx.zip

system, math, EZmath, TPmath1(fmath), MathX
Tangent see Tan AugMtah

D. Conversions and Formatting
"Numeric Conversion" in Delphi in a Nutshell,  pp. 515-523;
"Conversions/Formatting" on efg's Strings page;
Endian Notes

Function Name Description Source(s)
base conversions A program for converting numbers from/to Binary, Octal, Decimal, Hexadecimal. Also any user defined numeric base conversion is possible.
www.gu.edu.au/school/eng/mmt/Base.Zip 
 
BinToInt Converts a binary string into a long integer Clipper
BitOff Turns off the specified bit in a long integer Clipper
BitOn Turns on the specified bit in a long integer Clipper
BitSet Turns specified bit on in a long integer Clipper
BitToggle Toggles specified bit Clipper
Comma Formats a numeric of any type, inserting commas where approprite Clipper
CompToCurrency 'Comp' Integer to Currency
Function CompToCurrency(acomp: Comp): Currency; cdecl;

Delphi in a NutShell, pp. 166

System (D4)
CompToDouble 'Comp' Integer to Double
Function CompToDouble(acomp: Comp): Double; cdecl;

Delphi in a NutShell, pp. 167

System (D4)
Comp2Str Comp (64-bit integer) to String Calvert
CompToStr Complex to String TPmath1 (PaString)
Note:  Don't confuse 'Comp' as 'Complex' with the 'Comp' type
CurrencyToComp Currency to 'Comp' Integer
procedure CurrencyToComp(acurrency: Currency; var result: Comp); cdecl;

Delphi in a NutShell, pp. 173

System(D4)
Currency64ToString Delphi in a Nutshell, pp. 10-11  
DoubleToComp Double to 'Comp' Integer
procedure DoubleToComp(adouble: Double; var result: Comp); cdecl;

Delphi in a NutShell, pp. 186-187

System(D4)
DoubleToHex See efg's Exploring Numbers, Not-A-Number (NaN), and Infinity (INF)  
ExtendedToHex FUNCTION ExtendedToHex(CONST x: Extended): STRING;
  VAR
    // "overlay" and "x" occupy same memory location
    overlay: ARRAY[0..9] OF CHAR ABSOLUTE x;
    i : INTEGER;
BEGIN
  RESULT := '';
  // Use "logical" order instead of "little endian" order
  FOR i := Low(Overlay) TO High(Overlay) DO
  BEGIN
    RESULT := IntToHex( Byte(overlay[i]),2) + RESULT;
  END
END;

Example:
// PI = $4000C90FDAA22168C235
s := ExtendedToHex(PI);

 
FloatToDecimal Procedure FloatToDecimal(var DecVal: TFloatRec; const Value; ValueType: TFloatValue; Precision, Decimals: Integer);
Convert a floating-point value to a decimal representation suitable for further formattting.
SysUtils
FloatToStr Function FloatToStr(Value: Extended): string;
Float to String: Convert a floating-point value to a string.
The conversion uses general number format with 15 signficiant digits. Example: s := FloatToStr(x);
SysUtils,
TPmath1 (PaString)
FloatToStr Fix for Delphi 1 to handle NANs and INFs correctly. Tempest
FloatToStrF Function FloatToStrF(Value: Extended; Format: TFloatFormat; Precision, Digits: Integer): string;
Convert floating-point value to a string using a specified format, precision and digits. Format is ffGeneral, ffExponent, ffFixed, ffNumber or ffCurrency.

Handles NANs (non-a-number) and INFs (infinities, + or -).
Example: s := FloatToStr(x, ffGeneral, Precision, Digits);
SysUtils
FloatToStrF Fix for Delphi 1 to handle NANs and INFs correctly. Tempest
FloatToText Function FloatToText(Buffer: PChar; const Value; ValueType: TFloatValue; Format: TFloatFormat; Precision, Digits: Integer): Integer;
Convert floating-point value with specified format, precision and digits.
Null-terminated output string.
SysUtils
FloatToText Fix for Delphi 1 to handle NANs and INFs correctly. Tempest
FloatToTextFmt Function FloatToTextFmt(Buffer: PChar; const Value; ValueType: TFloatValue; Format: PChar): Integer;
Convert floating-point value to its decimal representation using the specified format. Null-terminated output string.
SysUtils
Format Function Format(const Format: string; const Args: array of const): string;

// Use like "C" sprintf
s := Format('%.3f times %d is %-16s', [Measurement, Value, Key]);

// for zero fill on left
s := Format('%3.3d', [i]); 

VAR
  d: INTEGER;
  w: INTEGER;
  x: Double;
. . .
x := -pi;
d := 4;
w := d + 3;
ShowMessage(Format('%*.*f', [w,d,x]));
ShowMessage(Format('%.*f', [d, x]));

SysUtils
FormatFloat Format floating-point value given format string. Format specifiers include 0-digit placeholder, #-digit placeholder (blanks), ',' - thousand separator, 'xx' or "xx"- as is, ';'-separate sections for +,-,0
Examples:
s := FormatFloat('##0.0', Factor);

VAR d: DOUBLE;

d := 123456789012345.25;
// displays 123,456,789,012,345.25
ShowMessage(FormatFloat(',#0.00', d));

d := 0.25;
// displays .25
ShowMessage(FormatFloat(',#.00', d));

SysUtils
HexToDouble See efg's Exploring Numbers, Not-A-Number (NaN), and Infinity (INF)  
HexToInt Converts a hexadecimal string into a long integer
(equivalent to StrToInt with '$' prefix)
Clipper
IntToBin Converts an integer to a binary string Clipper
IntToHex Function IntToHex(Value: Integer; Digits: Integer): string;

Function IntToHex(Value: Int64; Digits: Integer): string; overload; (D4)

Returns the hex representation of an integer

SysUtils
IntToStr Function IntToStr(Value: Integer): string; overload;

Function IntToStr(Value: Int64): string; overload; (D4)

Integer to String

SysUtils,
TPmath1 (PaString),
Calvert
IntToSTrPad0 Converts a number into a string and pads the string with zeros if it is less than Len characters long Calvert
IsAlpha, IsHex, IsNum, IsAlphaNum String validation routines in HyperString package
www.mindspring.com/~efd/tools.htm
 
LetNum TNumLet is a component that writes in words the number passed as a parameter.
http://delphi.icm.edu.pl/ftp/d10free/LetNum.zip 
 
LFill Pad with leading blanks (use for numeric alignment) TPmath1 (PaString)
NumConv Component to convert numbers from on numeric system to another
http://delphi.icm.edu.pl/ftp/d30free/numconv.zip
 
NumWords Express any number in words using English, Deutch, Francais, Espanol, Italiano, or Turkish. Automatic or manual selection of  language and currency
http://delphi.icm.edu.pl/ftp/d20free/numwords.zip
 
Pennies2Dollars Converts a Comp type that represents a certain number of pennies into a string with two decimal places. 123 => $1.23 Calvert
Real2Str Converts a double number into a string Calvert
Replace Replace all occurences of given string with another string. TPmath1 (PaString)
Roman function Roman(Number : longint) : string ;
Conversion to Roman Numeral

Also: Roman Numerals, www.delphiforfun.org/Programs/roman_numerals.htm 

Slightly modified version of Stockton's Roman function.

Stockton(wr-roman)
RFill Pad with trailing blanks (use for numeric alignment) TPmath1 (PaString)
Str Converts an integer-type or real-type expression to a string according to the Width and Decimals formatting parameters. System
StrChar Concatenate N occurences of given string TPmath1 (PaString)
StringForBytes Neil Rubenking's StringForBytes in the AllFuncs.pas unit of his ColorClue utility.  Given an Int64 number of bytes, returns 'nnn,nnn bytes' or ' nnn.nn KB' or 'nnn.nn MB' or 'nnn.nn GB'.  
StringToCurrency64 Delphi in a Nutshell, pp. 10-11  
Str2Comp Converts a String to a Comp Calvert
Str2Pennies Converts a String to a Comp Calvert
Str2Real Converts a string to a double number Calvert
StrToInt Function StrToInt(const S: string): Integer;

Converts given string to an integer value. (Actually uses Val procedure. See below.)

Prefix a string with a '$' to convert a hex value to an integer. Example: StrToInt('$' + 'C') returns the integer value 12.

In D4, the C-like '0x' prefix can also be used to denote a hex value.  For example,
i := StrToInt('0x1234');

SysUtils
StrToInt64 Function StrToInt64(const S: string): Int64; (D4) SysUtils
StrToIntDef Function StrToIntDef(const S: string; Default: Integer): Integer; SysUtils
StrToIntDef64 Function StrToInt64Def(const S: string; Default: Int64): Int64; (D4) SysUtils
StrToFloat Function StrToFloat(const S: string): Extended;
Convert given string to Extended float.
SysUtils
TFloatFormat TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency);
See FloatToStrF, FloatToText
SysUtils
TFloatRec TFloatRec =
record
  Exponent: Smallint;
  Negative: Boolean;
  Digits: array[0..20] of Char;
end;


TFloatRec is the FloatToDecimal result word.
SysUtils
TFloatValue TFloatValue = (fvExtended, fvCurrency);
TFloatValue is the type of the ValueType parameter of the FloatToText, FloatToTextFmt and TextToFloat functions and the FloatToDecimal procedure.
 
Trim Remove leading and trailing blanks SysUtils,
TPmath1 (PaString)
TrimLeft,
LTrim
Remove leading blanks SysUtils,
TPmath1 (PaString)
TrimRight,
RTrim
Remove trailing blanks SystUtils,
TPmath1 (PaString)
Unit Conversions Angle Conversions (cycle, radian, grad, degree)
Coordinate Conversions (Cartesian, polar)
Length (cm, inc, feet, meter, yard, km, mile)
Mass (kilogram, pound)
Pressure (Pascal, Bars, Atmosphere, Torr)
Temperature (Celsius, Kelvin, Fahrenheit)
Volume (liter, gallons)
JCLUnitConv
Val Procedure Val(S; var V; var Code: Integer);
Converts a string to its numeric representation. S is a string-type expression -- it must be a sequence of characters that form a signed whole number. V is an integer-type or real-type variable.

Val performs range checking differently depending upon the state of $R and the type of the parameter V: {$R+} -- an out-of-range value always genererates a run-time error. {$R-} -- the values for out-of-range vary depending upon the data type of V.

Use '$' prefix to convert hex to decimal.

In D4, also use '0x' prefix for hex value, for example,
Val('0x1234', i, Code);     // 4660 decimal

System
ValidFloat
FUNCTION ValidFloat(CONST s:  STRING):  BOOLEAN;
BEGIN
  RESULT := TRUE;
  TRY
    StrToFloat(s)
  EXCEPT
    ON EConvertError DO RESULT := FALSE
  END
END {ValidFloat};
SysUtils
xRound Clipper-like Round function Clipper
xStr Converts a number to a string with a width of 10 and no decimal places Clipper
xStrW Converts a number to a string of specified with with specifid decimal places Clipper
xVal Converts a string to a floating point value with error handling Clipper

 


E. Financial Functions

Function / Type Name Description Source(s)
DoubleDeclining
Balance
Function DoubleDecliningBalance(Cost, Salvage: Extended; Life, Period: Integer): Extended;

Depreciation using double-declining balance formula.

math
Financial Calculator The Financial Calculator calculates various types of time-dependent financial transactions, related to: 

1. Mortgage (Regular payment & Detailed payment schedule)

2. Loan (Payment, Principal & Term of Loans)

3. Investment (Final Value, Initial Principal, Interest Rate & Investment term of Term Deposits)

4. Annuity with Withdrawals (Principal, Withdrawal amount, & number of withdrawals)

5. Annuity with Deposits (Final Value, Regular deposits & Annuity term

http://delphi.icm.edu.pl/ftp/d30free/Fin_Calc.zip

 
FutureValue Function FutureValue(Rate: Extended; NPeriods: Integer; Payment, PresentValue: Extended; PaymentTime: TPaymentTime): Extended;

Future value of an investment.

math
InterestPayment Function InterestPayment(Rate: Extended; Period, NPeriods: Integer; PresentValue,FutureValue: Extended; PaymentTime: TPaymentTime): Extended;

Amount of the loan payment that is interest.

In D1-D5, there is a problem with InterestPayment and PeriodPayment ONLY for period one and ONLY for ptStartOfPeriod PaymentTime.  See efg's UseNet Posting about this problem and one possible fix.

math
InterestRate Function InterestRate(NPeriods: Integer;
Payment, PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;

Interest rate necessary to earn a specified amount.

math
InternalRateOfReturn Function InternalRateOfReturn(Guess: Extended;
const CashFlows: array of Double): Extended;

Rate of return based on cash-flow data.

math
Investments, Mortgage PC Magazine utility, PayEmOff, includes separate calculators for analyzing your mortgage and investments. These calculators can instantly show you the effect of changing the interest rate, payment amount, or number of months for investment or until payoff.  PC Magazine Utility, PayEmOff,  in Delphi.  
NetPresentValue Function NetPresentValue(Rate: Extended; const CashFlows: array of Double; PaymentTime: TPaymentTime): Extended;

Current value of a set of cash-flow values, taking the interest rate into account.

math
NumberOfPeriods Function NumberOfPeriods(Rate, Payment, PresentValue, FutureValue: Extended;PaymentTime: TPaymentTime): Extended;

Number of periods for an investment to reach a specified value.

math
Payment Function Payment(Rate: Extended; NPeriods: Integer;
PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;

Amount of loan payments, given the amount borrowed, the interest rate, and present and future values of the investment.

Returns the amount required to repay a debt, Borland  TI 1051D

math
PeriodPayment Function PeriodPayment(Rate: Extended; Period, NPeriods: Integer; PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;

Amount of the loan payment that is principal.

In D1-D5, there is a problem with InterestPayment and PeriodPayment ONLY for period one and ONLY for ptStartOfPeriod PaymentTime.  See efg's UseNet Posting about this problem and one possible fix.

math
PresentValue Function PresentValue(Rate: Extended; NPeriods: Integer; Payment, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;

Present value of an investment.

math
SLNDepreciation Function SLNDepreciation(Cost, Salvage: Extended; Life: Integer): Extended;

Straight-line depreciation of an investment.

math
SYDDepreciation Function SYDDepreciation(Cost, Salvage: Extended; Life, Period: Integer): Extended;

Sum-of-Years-Digits depreciation.

math
TPaymentTime type TPaymentTime = (ptEndOfPeriod, ptStartOfPeriod);  math

Business Calculator Component: www.flash.net/~wincsoft


F. Sorting, Discrete Mathematics

Function Name Math Description Source(s)
eclass determine equivalence classes from list recipes
eclazz determine equivalence classes from procedure recipes
indexx construct an index for an array recipes
piksr2 sort two arrays by straight insertion recipes
piksrt sort an array by straight insertion recipes
rank construct a rank table for an array recipes
QSort / DQSort Quick Sort TPmath1(stat)
shell sort an array by Shell's method recipes
sort sort an array by quicksort method recipes
sort2   recipes
sort3 sort, use an index to sort 3 or more arrays recipes

G. Miscellaneous Functions

Function Name Description Source(s)
ClearExceptions Clear FPU exception bits Tempest
CRC-16, CRC-32 See efg's CRC Lab Report for code and links  
Comparison Functions FltLE, FltLT, FltGE, FltGT, FltEQ, FltNE Tempest
ESBDigits number of digits of a positive integer ESBMaths
FloatIsZero Compares X to zero ESBMaths
Get8087x
Set8087x
function Get8087ControlWord: Word;
function Get8087Infinity: T8087Infinity;
function Get8087Precision: T8087Precision;
function Get8087Rounding: T8087Rounding;
function Get8087StatusWord: Word;   

function Set8087Infinity(const Infinity: T8087Infinity): T8087Infinity;

function Set8087Precision(const Precision: T8087Precision): T8087Precision; 

function Set8087Rounding(const Rounding: T8087Rounding): T8087Rounding; 

function Set8087ControlWord(const Control: Word): Word;

JCL8087
Get87ControlWord / Set87ControlWord 80x87 Control Word ESBmaths
GetControlWord / SetControlWord Get/Set FPU control word. See also Set8087CW. Tempest
GetExceptionMask / SetExceptionMask Get/Set FPU exception mask Tempest
GetRoundMode / SetRoundMode Get/Set FPU rounding mode Tempest
GetPrecisionMode / SetPrecisionMode Get/Set FPU precision mode Tempest
IsInfinity BOOLEAN function to determine if value is "not a number"

Also see efg's Exploring Numbers, Not-A-Number (NaN), and Infinity (INF)

Tempest
IsNAN BOOLEAN function to determine if value is +/- "infinity"

Also see efg's Exploring Numbers, Not-A-Number (NaN), and Infinity (INF)

Tempest
Set8087CW Set FPU control word.  See FPU Control Word Bits.

efg's Set8087CW and SetRoundMode rounding example gives these results:

Round Mode

Nearest
(IEEE/Banker's)
Down Up Truncate
Round(0/2) = 0
Round(1/2) = 0
Round(2/2) = 1
Round(3/2) = 2
Round(4/2) = 2
Round(5/2) = 2
Round(6/2) = 3
Round(7/2) = 4
Round(8/2) = 4
Round(9/2) = 4
Round(0/2) = 0
Round(1/2) = 0
Round(2/2) = 1
Round(3/2) = 1
Round(4/2) = 2
Round(5/2) = 2
Round(6/2) = 3
Round(7/2) = 3
Round(8/2) = 4
Round(9/2) = 4
Round(0/2) = 0
Round(1/2) = 1
Round(2/2) = 1
Round(3/2) = 2
Round(4/2) = 2
Round(5/2) = 3
Round(6/2) = 3
Round(7/2) = 4
Round(8/2) = 4
Round(9/2) = 5
Round(0/2) = 0
Round(1/2) = 0
Round(2/2) = 1
Round(3/2) = 1
Round(4/2) = 2
Round(5/2) = 2
Round(6/2) = 3
Round(7/2) = 3
Round(8/2) = 4
Round(9/2) = 4

Delphi in a NutShell, pp. 332-333

Steve Schafer's UseNet Post about FPU Control Word Bits

See comments in ESBMaths source code.

Affine: +INF and -INF are distinct values.
Projective: sign of INF is ignored.

// Default 8087 control word. FPU control register
// is set to this value.
// CAUTION: Setting this to an invalid value could
// cause unpredictable behavior.
VAR Default8087CW: Word = $1332;

//  The variable Default8087CW contains the default control word.
procedure Set8087CW(NewCW: Word);
asm
  MOV Default8087CW,AX
  FLDCW Default8087CW
end;

The OpenGL unit does this in its initialization code:
 
 Set8087CW($133F);

Charlie Calvert's "Turning off Floating Point Exceptions in BCB and Delphi" for Direct 3D, http://hometown.aol.com/charliecal/TechPapers/FloatingPoint.html

See Intel's Software and Hardware Considerations for FPU Exception Handlers for Intel Architecture Processors

Peter Below's UseNet Post explaining why the error "Floating Point Invalid Operation" occurs after calling a Delphi DLL from VC++

Stefan Hoffmeister's UseNet Post about FPU exception problems
Stefan Hoffmeister's UseNet Post with WreakHavoc example
John Herbster's UseNet Post with SetX87CW function and example

Bob Lee from 28 Aug 1999 UseNet Post:  "I have heard many people complain about MS DLL's altering the FPU control word.  Your only recourse is to wrap all calls to the DLL with a resetting of the controlword."

Maynard Philbrook's UseNet Post with ASM code for getting/setting control word.

See also GetControlWord / SetControlWord above.

system
Set87ControlWord see above ESBMaths
Sigmoid Robert Lee's "fast" routines, including sigmoid, in UseNet Post  

H. Sources Key

Source Description/Location
AugMath Augmented Math (what Borland left out)
www.engineeringobjects.com/AugMathUnit.htm 
Calvert Charlie Calvert's MathBox
http://homepages.borland.com/ccalvert/Downloads/MathBox.pas

32-bit replacement for MathBox and StrBox
http://homepages.borland.com/ccalvert/Downloads/CodeBox1.pas

Clipper Clipper Functions: Math/Conversion Functions
http://www.adpsi.com/clipfunc/cffuncs.htm 
ESBMaths
ESB Consultancy
Developers of Mathematical & Statistical
Software and Delphi Software.

ESBMaths is a collection of Integer and Floating Point Routines for Delphi. Includes probability and statistical related routines

Freeware ESBMaths with Source.  www.esbconsult.com

EZmath ?
ISPL Delphi interface for the Intel Signal Processing Library (5430 lines, 872 procedures and functions exported by NSP.DLL): http://home.t-online.de/home/Robert.Rossmair/nsp.htm
Intel Signal Processing Library:
http://developer.intel.com/vtune/perflibst/spl/index.htm
JCL8087 Delphi Jedi Code Library (JCL), JCL8087.pas unit
http://www.delphi-jedi.org/Jedi:CODELIBJCL 
JCLUnitConv Delphi Jedi Code Library (JCL), JCLUnitConv.pas unit
http://www.delphi-jedi.org/Jedi:CODELIBJCL 
math Borland's Delphi math unit
math1 www.lohninger.com/math1.html (not yet indexed above)
math2 www.lohninger.com/math2.html   (not yet indexed above)
mathlib2 ftp://ftp.wustl.edu/systems/ibmpc/garbo.uwasa.fi/turbopas/mathlib2.zip
ftp://garbo.uwasa.fi/pc/turbopas/mathlib2.zip
http://garbo.uwasa.fi/pc/turbopas.html
MathX www.razorsedgesoft.com/mathx.htm 
recipes Numerical Recipes Pascal shareware version
ftp://garbo.uwasa.fi/pc/turbopas/nrpas13.zip 
http://garbo.uwasa.fi/pc/turbopas.html 
RxLib www.rxlib.com  (file: MaxMin.PAS)

Stockton Dr. John Stockton's Pascal Maths Page
http://www.merlyn.demon.co.uk/pas-math.htm
System Borland's Delphi System unit
SysUtils Borland's Delphi SysUtils unit
Tempest Ray Lischner's FltMath unit (Math10.ZIP): www.tempest-sw.com/freeware (only compiles in Delphi 1)
TPmath1

TP Math

Jean DeBord's TPMath
www.unilim.fr/pages_perso/jean.debord/tpmath/tpmath.htm

Turbo Turbo Algorithms (C, Pascal, Basic, Prolog)
Keith Weiskamp, Namir Shamas, Ron Pronk
John Wiley, 1989 (Out of Print)
TurboAlgorithms.JPG (6242 bytes)

Links Verified 14 Jul 2000
Updated 29 Apr 2004


since 1 Nov 1998