home *** CD-ROM | disk | FTP | other *** search
/ Supercompiler 1997 / SUPERCOMPILER97.iso / Delphi 3.0 / DATA.Z / math.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1997-01-29  |  42.5 KB  |  1,458 lines

  1.  
  2. {*******************************************************}
  3. {                                                       }
  4. {       Delphi Runtime Library                          }
  5. {       Math Unit                                       }
  6. {                                                       }
  7. {       Copyright (C) 1996,97 Borland International     }
  8. {                                                       }
  9. {*******************************************************}
  10.  
  11. unit Math;
  12.  
  13. { This unit contains high-performance arithmetic, trigonometric, logorithmic,
  14.   statistical and financial calculation routines which supplement the math
  15.   routines that are part of the Delphi language or System unit. }
  16.  
  17. {$N+,S-}
  18.  
  19. interface
  20.  
  21. uses SysUtils;
  22.  
  23. const   { Ranges of the IEEE floating point types, including denormals }
  24.   MinSingle        =     1.5e-45;
  25.   MaxSingle        =     3.4e+38;
  26.   MinDouble        =     5.0e-324;
  27.   MaxDouble        =     1.7e+308;
  28.   MinExtended      =     3.4e-4932;
  29.   MaxExtended      =     1.1e+4932;
  30.   MinComp          =     -9.223372036854775807e+18;
  31.   MaxComp          =     9.223372036854775807e+18;
  32.  
  33. {-----------------------------------------------------------------------
  34. References:
  35.  
  36. 1) P.J. Plauger, "The Standard C Library", Prentice-Hall, 1992, Ch. 7.
  37. 2) W.J. Cody, Jr., and W. Waite, "Software Manual For the Elementary
  38.    Functions", Prentice-Hall, 1980.
  39. 3) Namir Shammas, "C/C++ Mathematical Algorithms for Scientists and Engineers",
  40.    McGraw-Hill, 1995, Ch 8.
  41. 4) H.T. Lau, "A Numerical Library in C for Scientists and Engineers",
  42.    CRC Press, 1994, Ch. 6.
  43. 5) "Pentium(tm) Processor User's Manual, Volume 3: Architecture
  44.    and Programming Manual", Intel, 1994
  45.  
  46. All angle parameters and results of trig functions are in radians.
  47.  
  48. Most of the following trig and log routines map directly to Intel 80387 FPU
  49. floating point machine instructions.  Input domains, output ranges, and
  50. error handling are determined largely by the FPU hardware.
  51. Routines coded in assembler favor the Pentium FPU pipeline architecture.
  52. -----------------------------------------------------------------------}
  53.  
  54. { Trigonometric functions }
  55. function ArcCos(X: Extended): Extended;  { IN: |X| <= 1  OUT: [0..PI] radians }
  56. function ArcSin(X: Extended): Extended;  { IN: |X| <= 1  OUT: [-PI/2..PI/2] radians }
  57.  
  58. { ArcTan2 calculates ArcTan(Y/X), and returns an angle in the correct quadrant.
  59.   IN: |Y| < 2^64, |X| < 2^64, X <> 0   OUT: [-PI..PI] radians }
  60. function ArcTan2(Y, X: Extended): Extended;
  61.  
  62. { SinCos is 2x faster than calling Sin and Cos separately for the same angle }
  63. procedure SinCos(Theta: Extended; var Sin, Cos: Extended) register;
  64. function Tan(X: Extended): Extended;
  65. function Cotan(X: Extended): Extended;           { 1 / tan(X), X <> 0 }
  66. function Hypot(X, Y: Extended): Extended;        { Sqrt(X**2 + Y**2) }
  67.  
  68. { Angle unit conversion routines }
  69. function DegToRad(Degrees: Extended): Extended;  { Radians := Degrees * PI / 180}
  70. function RadToDeg(Radians: Extended): Extended;  { Degrees := Radians * 180 / PI }
  71. function GradToRad(Grads: Extended): Extended;   { Radians := Grads * PI / 200 }
  72. function RadToGrad(Radians: Extended): Extended; { Grads := Radians * 200 / PI }
  73. function CycleToRad(Cycles: Extended): Extended; { Radians := Cycles * 2PI }
  74. function RadToCycle(Radians: Extended): Extended;{ Cycles := Radians / 2PI }
  75.  
  76. { Hyperbolic functions and inverses }
  77. function Cosh(X: Extended): Extended;
  78. function Sinh(X: Extended): Extended;
  79. function Tanh(X: Extended): Extended;
  80. function ArcCosh(X: Extended): Extended;   { IN: X >= 1 }
  81. function ArcSinh(X: Extended): Extended;
  82. function ArcTanh(X: Extended): Extended;   { IN: |X| <= 1 }
  83.  
  84. { Logorithmic functions }
  85. function LnXP1(X: Extended): Extended;   { Ln(X + 1), accurate for X near zero }
  86. function Log10(X: Extended): Extended;                     { Log base 10 of X}
  87. function Log2(X: Extended): Extended;                      { Log base 2 of X }
  88. function LogN(Base, X: Extended): Extended;                { Log base N of X }
  89.  
  90. { Exponential functions }
  91.  
  92. { IntPower: Raise base to an integral power.  Fast. }
  93. function IntPower(Base: Extended; Exponent: Integer): Extended register;
  94.  
  95. { Power: Raise base to any power.
  96.   For fractional exponents, or |exponents| > MaxInt, base must be > 0. }
  97. function Power(Base, Exponent: Extended): Extended;
  98.  
  99.  
  100. { Miscellaneous Routines }
  101.  
  102. { Frexp:  Separates the mantissa and exponent of X. }
  103. procedure Frexp(X: Extended; var Mantissa: Extended; var Exponent: Integer) register;
  104.  
  105. { Ldexp: returns X*2**P }
  106. function Ldexp(X: Extended; P: Integer): Extended register;
  107.  
  108. { Ceil: Smallest integer >= X, |X| < MaxInt }
  109. function Ceil(X: Extended):Integer;
  110.  
  111. { Floor: Largest integer <= X,  |X| < MaxInt }
  112. function Floor(X: Extended): Integer;
  113.  
  114. { Poly: Evaluates a uniform polynomial of one variable at value X.
  115.     The coefficients are ordered in increasing powers of X:
  116.     Coefficients[0] + Coefficients[1]*X + ... + Coefficients[N]*(X**N) }
  117. function Poly(X: Extended; const Coefficients: array of Double): Extended;
  118.  
  119. {-----------------------------------------------------------------------
  120. Statistical functions.
  121.  
  122. Common commercial spreadsheet macro names for these statistical and
  123. financial functions are given in the comments preceding each function.
  124. -----------------------------------------------------------------------}
  125.  
  126. { Mean:  Arithmetic average of values.  (AVG):  SUM / N }
  127. function Mean(const Data: array of Double): Extended;
  128.  
  129. { Sum: Sum of values.  (SUM) }
  130. function Sum(const Data: array of Double): Extended register;
  131. function SumInt(const Data: array of Integer): Integer register;
  132. function SumOfSquares(const Data: array of Double): Extended;
  133. procedure SumsAndSquares(const Data: array of Double;
  134.   var Sum, SumOfSquares: Extended) register;
  135.  
  136. { MinValue: Returns the smallest signed value in the data array (MIN) }
  137. function MinValue(const Data: array of Double): Double;
  138. function MinIntValue(const Data: array of Integer): Integer;
  139.  
  140. { MaxValue: Returns the largest signed value in the data array (MAX) }
  141. function MaxValue(const Data: array of Double): Double;
  142. function MaxIntValue(const Data: array of Integer): Integer;
  143.  
  144. { Standard Deviation (STD): Sqrt(Variance). aka Sample Standard Deviation }
  145. function StdDev(const Data: array of Double): Extended;
  146.  
  147. { MeanAndStdDev calculates Mean and StdDev in one call. }
  148. procedure MeanAndStdDev(const Data: array of Double; var Mean, StdDev: Extended);
  149.  
  150. { Population Standard Deviation (STDP): Sqrt(PopnVariance).
  151.   Used in some business and financial calculations. }
  152. function PopnStdDev(const Data: array of Double): Extended;
  153.  
  154. { Variance (VARS): TotalVariance / (N-1). aka Sample Variance }
  155. function Variance(const Data: array of Double): Extended;
  156.  
  157. { Population Variance (VAR or VARP): TotalVariance/ N }
  158. function PopnVariance(const Data: array of Double): Extended;
  159.  
  160. { Total Variance: SUM(i=1,N)[(X(i) - Mean)**2] }
  161. function TotalVariance(const Data: array of Double): Extended;
  162.  
  163. { Norm:  The Euclidean L2-norm.  Sqrt(SumOfSquares) }
  164. function Norm(const Data: array of Double): Extended;
  165.  
  166. { MomentSkewKurtosis: Calculates the core factors of statistical analysis:
  167.   the first four moments plus the coefficients of skewness and kurtosis.
  168.   M1 is the Mean.  M2 is the Variance.
  169.   Skew reflects symmetry of distribution: M3 / (M2**(3/2))
  170.   Kurtosis reflects flatness of distribution: M4 / Sqr(M2) }
  171. procedure MomentSkewKurtosis(const Data: array of Double;
  172.   var M1, M2, M3, M4, Skew, Kurtosis: Extended);
  173.  
  174. { RandG produces random numbers with Gaussian distribution about the mean.
  175.   Useful for simulating data with sampling errors. }
  176. function RandG(Mean, StdDev: Extended): Extended;
  177.  
  178. {-----------------------------------------------------------------------
  179. Financial functions.  Standard set from Quattro Pro.
  180.  
  181. Parameter conventions:
  182.  
  183. From the point of view of A, amounts received by A are positive and
  184. amounts disbursed by A are negative (e.g. a borrower's loan repayments
  185. are regarded by the borrower as negative).
  186.  
  187. Interest rates are per payment period.  11% annual percentage rate on a
  188. loan with 12 payments per year would be (11 / 100) / 12 = 0.00916667
  189.  
  190. -----------------------------------------------------------------------}
  191.  
  192. type
  193.   TPaymentTime = (ptEndOfPeriod, ptStartOfPeriod);
  194.  
  195. { Double Declining Balance (DDB) }
  196. function DoubleDecliningBalance(Cost, Salvage: Extended;
  197.   Life, Period: Integer): Extended;
  198.  
  199. { Future Value (FVAL) }
  200. function FutureValue(Rate: Extended; NPeriods: Integer; Payment, PresentValue:
  201.   Extended; PaymentTime: TPaymentTime): Extended;
  202.  
  203. { Interest Payment (IPAYMT)  }
  204. function InterestPayment(Rate: Extended; Period, NPeriods: Integer; PresentValue,
  205.   FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  206.  
  207. { Interest Rate (IRATE) }
  208. function InterestRate(NPeriods: Integer;
  209.   Payment, PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  210.  
  211. { Internal Rate of Return. (IRR) Needs array of cash flows. }
  212. function InternalRateOfReturn(Guess: Extended;
  213.   const CashFlows: array of Double): Extended;
  214.  
  215. { Number of Periods (NPER) }
  216. function NumberOfPeriods(Rate, Payment, PresentValue, FutureValue: Extended;
  217.   PaymentTime: TPaymentTime): Extended;
  218.  
  219. { Net Present Value. (NPV) Needs array of cash flows. }
  220. function NetPresentValue(Rate: Extended; const CashFlows: array of Double;
  221.   PaymentTime: TPaymentTime): Extended;
  222.  
  223. { Payment (PAYMT) }
  224. function Payment(Rate: Extended; NPeriods: Integer;
  225.   PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  226.  
  227. { Period Payment (PPAYMT) }
  228. function PeriodPayment(Rate: Extended; Period, NPeriods: Integer;
  229.   PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  230.  
  231. { Present Value (PVAL) }
  232. function PresentValue(Rate: Extended; NPeriods: Integer;
  233.   Payment, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  234.  
  235. { Straight Line depreciation (SLN) }
  236. function SLNDepreciation(Cost, Salvage: Extended; Life: Integer): Extended;
  237.  
  238. { Sum-of-Years-Digits depreciation (SYD) }
  239. function SYDDepreciation(Cost, Salvage: Extended; Life, Period: Integer): Extended;
  240.  
  241. type
  242.   EInvalidArgument = class(EMathError) end;
  243.  
  244. implementation
  245.  
  246. function Annuity2(R: Extended; N: Integer; PaymentTime: TPaymentTime;
  247.   var CompoundRN: Extended): Extended; Forward;
  248. function AnnuityF(R:Extended; N: Integer): Extended; Forward;
  249. function Compound(R: Extended; N: Integer): Extended; Forward;
  250. function RelSmall(X, Y: Extended): Boolean; Forward;
  251.  
  252. type
  253.   TPoly = record
  254.     Neg, Pos, DNeg, DPos: Extended
  255.   end;
  256.  
  257. const
  258.   MaxIterations = 15;
  259.  
  260. procedure ArgError(const Msg: string);
  261. begin
  262.   raise EInvalidArgument.Create(Msg);
  263. end;
  264.  
  265. function DegToRad(Degrees: Extended): Extended;  { Radians := Degrees * PI / 180 }
  266. begin
  267.   Result := Degrees * (PI / 180);
  268. end;
  269.  
  270. function RadToDeg(Radians: Extended): Extended;  { Degrees := Radians * 180 / PI }
  271. begin
  272.   Result := Radians * (180 / PI);
  273. end;
  274.  
  275. function GradToRad(Grads: Extended): Extended;   { Radians := Grads * PI / 200 }
  276. begin
  277.   Result := Grads * (PI / 200);
  278. end;
  279.  
  280. function RadToGrad(Radians: Extended): Extended; { Grads := Radians * 200 / PI}
  281. begin
  282.   Result := Radians * (200 / PI);
  283. end;
  284.  
  285. function CycleToRad(Cycles: Extended): Extended; { Radians := Cycles * 2PI }
  286. begin
  287.   Result := Cycles * (2 * PI);
  288. end;
  289.  
  290. function RadToCycle(Radians: Extended): Extended;{ Cycles := Radians / 2PI }
  291. begin
  292.   Result := Radians / (2 * PI);
  293. end;
  294.  
  295. function LnXP1(X: Extended): Extended;
  296. { Return ln(1 + X).  Accurate for X near 0. }
  297. asm
  298.         FLDLN2
  299.         MOV     AX,WORD PTR X+8               { exponent }
  300.         FLD     X
  301.         CMP     AX,$3FFD                      { .4225 }
  302.         JB      @@1
  303.         FLD1
  304.         FADD
  305.         FYL2X
  306.         JMP     @@2
  307. @@1:
  308.         FYL2XP1
  309. @@2:
  310.         FWAIT
  311. end;
  312.  
  313. { Invariant: Y >= 0 & Result*X**Y = X**I.  Init Y = I and Result = 1. }
  314. {function IntPower(X: Extended; I: Integer): Extended;
  315. var
  316.   Y: Integer;
  317. begin
  318.   Y := Abs(I);
  319.   Result := 1.0;
  320.   while Y > 0 do begin
  321.     while not Odd(Y) do
  322.     begin
  323.       Y := Y shr 1;
  324.       X := X * X
  325.     end;
  326.     Dec(Y);
  327.     Result := Result * X
  328.   end;
  329.   if I < 0 then Result := 1.0 / Result
  330. end;
  331. }
  332. function IntPower(Base: Extended; Exponent: Integer): Extended;
  333. asm
  334.         mov     ecx, eax
  335.         cdq
  336.         fld1                      { Result := 1 }
  337.         xor     eax, edx
  338.         sub     eax, edx          { eax := Abs(Exponent) }
  339.         jz      @@3
  340.         fld     Base
  341.         jmp     @@2
  342. @@1:    fmul    ST, ST            { X := Base * Base }
  343. @@2:    shr     eax,1
  344.         jnc     @@1
  345.         fmul    ST(1),ST          { Result := Result * X }
  346.         jnz     @@1
  347.         fstp    st                { pop X from FPU stack }
  348.         cmp     ecx, 0
  349.         jge     @@3
  350.         fld1
  351.         fdivrp                    { Result := 1 / Result }
  352. @@3:
  353.         fwait
  354. end;
  355.  
  356. function Compound(R: Extended; N: Integer): Extended;
  357. { Return (1 + R)**N. }
  358. begin
  359.   Result := IntPower(1.0 + R, N)
  360. end;
  361.  
  362. function AnnuityF(R:Extended; N: Integer): Extended;
  363. {Return (((1+R)**N)-1)/R, the annuity growth factor}
  364. begin
  365.   { 6.1E-5 approx= 2**-14 }
  366.     if ( ABS(R)<6.1E-5 ) then
  367.         AnnuityF := N*(1+(N-1)*R/2) {linear approximation for small R}
  368.     else
  369.       AnnuityF := (Exp(N*LNXP1(R))-1)/R;
  370. end; {AnnuityF}
  371.  
  372.  
  373. function Annuity2(R: Extended; N: Integer; PaymentTime: TPaymentTime;
  374.   var CompoundRN: Extended): Extended;
  375. { Set CompoundRN to Compound(R, N),
  376.     return (1+Rate*PaymentTime)*(Compound(R,N)-1)/R;
  377. }
  378. begin
  379.   if R = 0.0 then
  380.   begin
  381.     CompoundRN := 1.0;
  382.     Result := N;
  383.   end
  384.   else
  385.   begin
  386.     { 6.1E-5 approx= 2**-14 }
  387.     if Abs(R) < 6.1E-5 then
  388.     begin
  389.       CompoundRN := Exp(N * LnXP1(R));
  390.       Result := N*(1+(N-1)*R/2);
  391.     end
  392.     else
  393.     begin
  394.       CompoundRN := Compound(R, N);
  395.       Result := (CompoundRN-1) / R
  396.     end;
  397.     if PaymentTime = ptStartOfPeriod then
  398.       Result := Result * (1 + R);
  399.   end;
  400. end; {Annuity2}
  401.  
  402.  
  403. procedure PolyX(const A: array of Double; X: Extended; var Poly: TPoly);
  404. { Compute A[0] + A[1]*X + ... + A[N]*X**N and X * its derivative.
  405.   Accumulate positive and negative terms separately. }
  406. var
  407.   I: Integer;
  408.   Neg, Pos, DNeg, DPos: Extended;
  409. begin
  410.   Neg := 0.0;
  411.   Pos := 0.0;
  412.   DNeg := 0.0;
  413.   DPos := 0.0;
  414.     for I := High(A) downto  Low(A) do
  415.   begin
  416.     DNeg := X * DNeg + Neg;
  417.     Neg := Neg * X;
  418.     DPos := X * DPos + Pos;
  419.     Pos := Pos * X;
  420.     if A[I] >= 0.0 then
  421.       Pos := Pos + A[I]
  422.     else
  423.       Neg := Neg + A[I]
  424.   end;
  425.   Poly.Neg := Neg;
  426.   Poly.Pos := Pos;
  427.   Poly.DNeg := DNeg * X;
  428.   Poly.DPos := DPos * X;
  429. end; {PolyX}
  430.  
  431.  
  432. function RelSmall(X, Y: Extended): Boolean;
  433. { Returns True if X is small relative to Y }
  434. const
  435.   C1: Double = 1E-15;
  436.   C2: Double = 1E-12;
  437. begin
  438.   Result := Abs(X) < (C1 + C2 * Abs(Y))
  439. end;
  440.  
  441. { Math functions. }
  442.  
  443. function ArcCos(X: Extended): Extended;
  444. begin
  445.   Result := ArcTan2(Sqrt(1 - X*X), X);
  446. end;
  447.  
  448. function ArcSin(X: Extended): Extended;
  449. begin
  450.   Result := ArcTan2(X, Sqrt(1 - X*X))
  451. end;
  452.  
  453. function ArcTan2(Y, X: Extended): Extended;
  454. asm
  455.         FLD     Y
  456.         FLD     X
  457.         FPATAN
  458.         FWAIT
  459. end;
  460.  
  461. function Tan(X: Extended): Extended;
  462. {  Tan := Sin(X) / Cos(X) }
  463. asm
  464.         FLD    X
  465.         FPTAN
  466.         FSTP   ST(0)      { FPTAN pushes 1.0 after result }
  467.         FWAIT
  468. end;
  469.  
  470. function CoTan(X: Extended): Extended;
  471. { CoTan := Cos(X) / Sin(X) = 1 / Tan(X) }
  472. asm
  473.         FLD   X
  474.         FPTAN
  475.         FDIVRP
  476.         FWAIT
  477. end;
  478.  
  479. function Hypot(X, Y: Extended): Extended;
  480. { formula: Sqrt(X*X + Y*Y)
  481.   implemented as:  |Y|*Sqrt(1+Sqr(X/Y)), |X| < |Y| for greater precision
  482. var
  483.   Temp: Extended;
  484. begin
  485.   X := Abs(X);
  486.   Y := Abs(Y);
  487.   if X > Y then
  488.   begin
  489.     Temp := X;
  490.     X := Y;
  491.     Y := Temp;
  492.   end;
  493.   if X = 0 then
  494.     Result := Y
  495.   else         // Y > X, X <> 0, so Y > 0
  496.     Result := Y * Sqrt(1 + Sqr(X/Y));
  497. end;
  498. }
  499. asm
  500.         FLD     Y
  501.         FABS
  502.         FLD     X
  503.         FABS
  504.         FCOM
  505.         FNSTSW  AX
  506.         TEST    AH,$F
  507.         JNZ      @@1        // if ST > ST(1) then swap
  508.         FXCH    ST(1)      // put larger number in ST(1)
  509. @@1:    FLDZ
  510.         FCOMP
  511.         FNSTSW  AX
  512.         TEST    AH,$4      // if ST = 0, return ST(1)
  513.         JZ      @@2
  514.         FSTP    ST         // eat ST(0)
  515.         JMP     @@3
  516. @@2:    FDIV    ST,ST(1)   // ST := ST / ST(1)
  517.         FMUL    ST,ST      // ST := ST * ST
  518.         FLD1
  519.         FADD               // ST := ST + 1
  520.         FSQRT              // ST := Sqrt(ST)
  521.         FMUL               // ST(1) := ST * ST(1); Pop ST
  522. @@3:    FWAIT
  523. end;
  524.  
  525.  
  526. procedure SinCos(Theta: Extended; var Sin, Cos: Extended);
  527. asm
  528.         FLD     Theta
  529.         FSINCOS
  530.         FSTP    tbyte ptr [edx]    // Cos
  531.         FSTP    tbyte ptr [eax]    // Sin
  532.         FWAIT
  533. end;
  534.  
  535. { Extract exponent and mantissa from X }
  536. procedure Frexp(X: Extended; var Mantissa: Extended; var Exponent: Integer);
  537. { Mantissa ptr in EAX, Exponent ptr in EDX }
  538. asm
  539.         FLD     X
  540.         PUSH    EAX
  541.         MOV     dword ptr [edx], 0    { if X = 0, return 0 }
  542.  
  543.         FTST
  544.         FSTSW   AX
  545.         FWAIT
  546.         SAHF
  547.         JZ      @@Done
  548.  
  549.         FXTRACT                 // ST(1) = exponent, (pushed) ST = fraction
  550.         FXCH
  551.  
  552. // The FXTRACT instruction normalizes the fraction 1 bit higher than
  553. // wanted for the definition of frexp() so we need to tweak the result
  554. // by scaling the fraction down and incrementing the exponent.
  555.  
  556.         FISTP   dword ptr [edx]
  557.         FLD1
  558.         FCHS
  559.         FXCH
  560.         FSCALE                  // scale fraction
  561.         INC     dword ptr [edx] // exponent biased to match
  562.         FSTP ST(1)              // discard -1, leave fraction as TOS
  563.  
  564. @@Done:
  565.         POP     EAX
  566.         FSTP    tbyte ptr [eax]
  567.         FWAIT
  568. end;
  569.  
  570. function Ldexp(X: Extended; P: Integer): Extended;
  571.   { Result := X * (2^P) }
  572. asm
  573.         PUSH    EAX
  574.         FILD    dword ptr [ESP]
  575.         FLD     X
  576.         FSCALE
  577.         POP     EAX
  578.         FSTP    ST(1)
  579.         FWAIT
  580. end;
  581.  
  582. function Ceil(X: Extended): Integer;
  583. begin
  584.   Result := Trunc(X);
  585.   if Frac(X) > 0 then
  586.     Inc(Result);
  587. end;
  588.  
  589. function Floor(X: Extended): Integer;
  590. begin
  591.   Result := Trunc(X);
  592.   if Frac(X) < 0 then
  593.     Dec(Result);
  594. end;
  595.  
  596. { Conversion of bases:  Log.b(X) = Log.a(X) / Log.a(b)  }
  597.  
  598. function Log10(X: Extended): Extended;
  599.   { Log.10(X) := Log.2(X) * Log.10(2) }
  600. asm
  601.         FLDLG2     { Log base ten of 2 }
  602.         FLD     X
  603.         FYL2X
  604.         FWAIT
  605. end;
  606.  
  607. function Log2(X: Extended): Extended;
  608. asm
  609.         FLD1
  610.         FLD     X
  611.         FYL2X
  612.         FWAIT
  613. end;
  614.  
  615. function LogN(Base, X: Extended): Extended;
  616. { Log.N(X) := Log.2(X) / Log.2(N) }
  617. asm
  618.         FLD1
  619.         FLD     X
  620.         FYL2X
  621.         FLD1
  622.         FLD     Base
  623.         FYL2X
  624.         FDIV
  625.         FWAIT
  626. end;
  627.  
  628. function Poly(X: Extended; const Coefficients: array of Double): Extended;
  629. { Horner's method }
  630. var
  631.   I: Integer;
  632. begin
  633.   Result := Coefficients[High(Coefficients)];
  634.   for I := High(Coefficients)-1 downto Low(Coefficients) do
  635.     Result := Result * X + Coefficients[I];
  636. end;
  637.  
  638. function Power(Base, Exponent: Extended): Extended;
  639. begin
  640.   if Exponent = 0.0 then
  641.     Result := 1.0               { n**0 = 1 }
  642.   else if (Base = 0.0) and (Exponent > 0.0) then
  643.     Result := 0.0               { 0**n = 0, n > 0 }
  644.   else if (Frac(Exponent) = 0.0) and (Abs(Exponent) <= MaxInt) then
  645.     Result := IntPower(Base, Trunc(Exponent))
  646.   else
  647.     Result := Exp(Exponent * Ln(Base))
  648. end;
  649.  
  650. { Hyperbolic functions }
  651.  
  652. function CoshSinh(X: Extended; Factor: Double): Extended;
  653. begin
  654.   Result := Exp(X) / 2;
  655.   Result := Result + Factor / Result;
  656. end;
  657.  
  658. function Cosh(X: Extended): Extended;
  659. begin
  660.   Result := CoshSinh(X, 0.25)
  661. end;
  662.  
  663. function Sinh(X: Extended): Extended;
  664. begin
  665.   Result := CoshSinh(X, -0.25)
  666. end;
  667.  
  668. const
  669.   MaxTanhDomain = 5678.22249441322; // Ln(MaxExtended)/2
  670.  
  671. function Tanh(X: Extended): Extended;
  672. begin
  673.   if X > MaxTanhDomain then
  674.     Result := 1.0
  675.   else if X < -MaxTanhDomain then
  676.     Result := -1.0
  677.   else
  678.   begin
  679.     Result := Exp(X);
  680.     Result := Result * Result;
  681.     Result := (Result - 1.0) / (Result + 1.0)
  682.   end;
  683. end;
  684.  
  685. function ArcCosh(X: Extended): Extended;
  686. begin
  687.   if X <= 1.0 then
  688.     Result := 0.0
  689.   else if X > 1.0e10 then
  690.     Result := Ln(2) + Ln(X)
  691.   else
  692.     Result := Ln(X + Sqrt((X - 1.0) * (X + 1.0)));
  693. end;
  694.  
  695. function ArcSinh(X: Extended): Extended;
  696. var
  697.   Neg: Boolean;
  698. begin
  699.   if X = 0 then
  700.     Result := 0
  701.   else
  702.   begin
  703.     Neg := (X < 0);
  704.     X := Abs(X);
  705.     if X > 1.0e10 then
  706.       Result := Ln(2) + Ln(X)
  707.     else
  708.     begin
  709.       Result := X*X;
  710.       Result := LnXP1(X + Result / (1 + Sqrt(1 + Result)));
  711.     end;
  712.     if Neg then Result := -Result;
  713.   end;
  714. end;
  715.  
  716. function ArcTanh(X: Extended): Extended;
  717. var
  718.   Neg: Boolean;
  719. begin
  720.   if X = 0 then
  721.     Result := 0
  722.   else
  723.   begin
  724.     Neg := (X < 0);
  725.     X := Abs(X);
  726.     if X >= 1 then
  727.       Result := MaxExtended
  728.     else
  729.       Result := 0.5 * LnXP1((2.0 * X) / (1.0 - X));
  730.     if Neg then Result := -Result;
  731.   end;
  732. end;
  733.  
  734. { Statistical functions }
  735.  
  736. function Mean(const Data: array of Double): Extended;
  737. begin
  738.   Result := SUM(Data) / (High(Data) - Low(Data) + 1)
  739. end;
  740.  
  741. function MinValue(const Data: array of Double): Double;
  742. var
  743.   I: Integer;
  744. begin
  745.   Result := Data[Low(Data)];
  746.   for I := Low(Data) + 1 to High(Data) do
  747.     if Result > Data[I] then
  748.       Result := Data[I];
  749. end;
  750.  
  751. function MinIntValue(const Data: array of Integer): Integer;
  752. var
  753.   I: Integer;
  754. begin
  755.   Result := Data[Low(Data)];
  756.   for I := Low(Data) + 1 to High(Data) do
  757.     if Result > Data[I] then
  758.       Result := Data[I];
  759. end;
  760.  
  761. function MaxValue(const Data: array of Double): Double;
  762. var
  763.   I: Integer;
  764. begin
  765.   Result := Data[Low(Data)];
  766.   for I := Low(Data) + 1 to High(Data) do
  767.     if Result < Data[I] then
  768.       Result := Data[I];
  769. end;
  770.  
  771. function MaxIntValue(const Data: array of Integer): Integer;
  772. var
  773.   I: Integer;
  774. begin
  775.   Result := Data[Low(Data)];
  776.   for I := Low(Data) + 1 to High(Data) do
  777.     if Result < Data[I] then
  778.       Result := Data[I];
  779. end;
  780.  
  781. procedure MeanAndStdDev(const Data: array of Double; var Mean, StdDev: Extended);
  782. var
  783.   S: Extended;
  784.   N,I: Integer;
  785. begin
  786.   N := High(Data)- Low(Data) + 1;
  787.   if N = 1 then
  788.   begin
  789.     Mean := Data[0];
  790.     StdDev := Data[0];
  791.     Exit;
  792.   end;
  793.   Mean := Sum(Data) / N;
  794.   S := 0;               // sum differences from the mean, for greater accuracy
  795.   for I := Low(Data) to High(Data) do
  796.     S := S + Sqr(Mean - Data[I]);
  797.   StdDev := Sqrt(S / (N - 1));
  798. end;
  799.  
  800. procedure MomentSkewKurtosis(const Data: array of Double;
  801.   var M1, M2, M3, M4, Skew, Kurtosis: Extended);
  802. var
  803.   Sum, SumSquares, SumCubes, SumQuads, OverN, Accum, M1Sqr, S2N, S3N: Extended;
  804.   I: Integer;
  805. begin
  806.   OverN := 1 / (High(Data) - Low(Data) + 1);
  807.   Sum := 0;
  808.   SumSquares := 0;
  809.   SumCubes := 0;
  810.   SumQuads := 0;
  811.   for I := Low(Data) to High(Data) do
  812.   begin
  813.     Sum := Sum + Data[I];
  814.     Accum := Sqr(Data[I]);
  815.     SumSquares := SumSquares + Accum;
  816.     Accum := Accum*Data[I];
  817.     SumCubes := SumCubes + Accum;
  818.     SumQuads := SumQuads + Accum*Data[I];
  819.   end;
  820.   M1 := Sum * OverN;
  821.   M1Sqr := Sqr(M1);
  822.   S2N := SumSquares * OverN;
  823.   S3N := SumCubes * OverN;
  824.   M2 := S2N - M1Sqr;
  825.   M3 := S3N - (M1 * 3 * S2N) + 2*M1Sqr*M1;
  826.   M4 := (SumQuads * OverN) - (M1 * 4 * S3N) + (M1Sqr*6*S2N - 3*Sqr(M1Sqr));
  827.   Skew := M3 * Power(M2, -3/2);   // = M3 / Power(M2, 3/2)
  828.   Kurtosis := M4 / Sqr(M2);
  829. end;
  830.  
  831. function Norm(const Data: array of Double): Extended;
  832. begin
  833.   Result := Sqrt(SumOfSquares(Data));
  834. end;
  835.  
  836. function PopnStdDev(const Data: array of Double): Extended;
  837. begin
  838.   Result := Sqrt(PopnVariance(Data))
  839. end;
  840.  
  841. function PopnVariance(const Data: array of Double): Extended;
  842. begin
  843.   Result := TotalVariance(Data) / (High(Data) - Low(Data) + 1)
  844. end;
  845.  
  846. function RandG(Mean, StdDev: Extended): Extended;
  847. { Marsaglia-Bray algorithm }
  848. var
  849.   U1, S2: Extended;
  850. begin
  851.   repeat
  852.     U1 := 2*Random - 1;
  853.     S2 := Sqr(U1) + Sqr(2*Random-1);
  854.   until S2 < 1;
  855.   Result := Sqrt(-2*Ln(S2)/S2) * U1 * StdDev + Mean;
  856. end;
  857.  
  858. function StdDev(const Data: array of Double): Extended;
  859. begin
  860.   Result := Sqrt(Variance(Data))
  861. end;
  862.  
  863. procedure RaiseOverflowError; forward;
  864.  
  865. function SumInt(const Data: array of Integer): Integer;
  866. {var
  867.   I: Integer;
  868. begin
  869.   Result := 0;
  870.   for I := Low(Data) to High(Data) do
  871.     Result := Result + Data[I]
  872. end; }
  873. asm  // IN: EAX = ptr to Data, EDX = High(Data) = Count - 1
  874.      // loop unrolled 4 times, 5 clocks per loop, 1.2 clocks per datum
  875.       PUSH EBX
  876.       MOV  ECX, EAX         // ecx = ptr to data
  877.       MOV  EBX, EDX
  878.       XOR  EAX, EAX
  879.       AND  EDX, not 3
  880.       AND  EBX, 3
  881.       SHL  EDX, 2
  882.       JMP  @Vector.Pointer[EBX*4]
  883. @Vector:
  884.       DD @@1
  885.       DD @@2
  886.       DD @@3
  887.       DD @@4
  888. @@4:
  889.       ADD  EAX, [ECX+12+EDX]
  890.       JO   RaiseOverflowError
  891. @@3:
  892.       ADD  EAX, [ECX+8+EDX]
  893.       JO   RaiseOverflowError
  894. @@2:
  895.       ADD  EAX, [ECX+4+EDX]
  896.       JO   RaiseOverflowError
  897. @@1:
  898.       ADD  EAX, [ECX+EDX]
  899.       JO   RaiseOverflowError
  900.       SUB  EDX,16
  901.       JNS  @@4
  902.       POP  EBX
  903. end;
  904.  
  905. procedure RaiseOverflowError;
  906. begin
  907.   raise EIntOverflow.Create(SIntOverflow);
  908. end;
  909.  
  910. function SUM(const Data: array of Double): Extended;
  911. {var
  912.   I: Integer;
  913. begin
  914.   Result := 0.0;
  915.   for I := Low(Data) to High(Data) do
  916.     Result := Result + Data[I]
  917. end; }
  918. asm  // IN: EAX = ptr to Data, EDX = High(Data) = Count - 1
  919.      // Uses 4 accumulators to minimize read-after-write delays and loop overhead
  920.      // 5 clocks per loop, 4 items per loop = 1.2 clocks per item
  921.        FLDZ
  922.        MOV      ECX, EDX
  923.        FLD      ST(0)
  924.        AND      EDX, not 3
  925.        FLD      ST(0)
  926.        AND      ECX, 3
  927.        FLD      ST(0)
  928.        SHL      EDX, 3      // count * sizeof(Double) = count * 8
  929.        JMP      @Vector.Pointer[ECX*4]
  930. @Vector:
  931.        DD @@1
  932.        DD @@2
  933.        DD @@3
  934.        DD @@4
  935. @@4:   FADD     qword ptr [EAX+EDX+24]    // 1
  936.        FXCH     ST(3)                     // 0
  937. @@3:   FADD     qword ptr [EAX+EDX+16]    // 1
  938.        FXCH     ST(2)                     // 0
  939. @@2:   FADD     qword ptr [EAX+EDX+8]     // 1
  940.        FXCH     ST(1)                     // 0
  941. @@1:   FADD     qword ptr [EAX+EDX]       // 1
  942.        FXCH     ST(2)                     // 0
  943.        SUB      EDX, 32
  944.        JNS      @@4
  945.        FADDP    ST(3),ST                  // ST(3) := ST + ST(3); Pop ST
  946.        FADD                               // ST(1) := ST + ST(1); Pop ST
  947.        FADD                               // ST(1) := ST + ST(1); Pop ST
  948.        FWAIT
  949. end;
  950.  
  951. function SumOfSquares(const Data: array of Double): Extended;
  952. var
  953.   I: Integer;
  954. begin
  955.   Result := 0.0;
  956.   for I := Low(Data) to High(Data) do
  957.     Result := Result + Sqr(Data[I]);
  958. end;
  959.  
  960. procedure SumsAndSquares(const Data: array of Double; var Sum, SumOfSquares: Extended);
  961. {var
  962.   I: Integer;
  963. begin
  964.   Sum := 0;
  965.   SumOfSquares := 0;
  966.   for I := Low(Data) to High(Data) do
  967.   begin
  968.     Sum := Sum + Data[I];
  969.     SumOfSquares := SumOfSquares + Data[I]*Data[I];
  970.   end;
  971. end;  }
  972. asm  // IN:  EAX = ptr to Data
  973.      //      EDX = High(Data) = Count - 1
  974.      //      ECX = ptr to Sum
  975.      // Est. 17 clocks per loop, 4 items per loop = 4.5 clocks per data item
  976.        FLDZ                 // init Sum accumulator
  977.        PUSH     ECX
  978.        MOV      ECX, EDX
  979.        FLD      ST(0)       // init Sqr1 accum.
  980.        AND      EDX, not 3
  981.        FLD      ST(0)       // init Sqr2 accum.
  982.        AND      ECX, 3
  983.        FLD      ST(0)       // init/simulate last data item left in ST
  984.        SHL      EDX, 3      // count * sizeof(Double) = count * 8
  985.        JMP      @Vector.Pointer[ECX*4]
  986. @Vector:
  987.        DD @@1
  988.        DD @@2
  989.        DD @@3
  990.        DD @@4
  991. @@4:   FADD                            // Sqr2 := Sqr2 + Sqr(Data4); Pop Data4
  992.        FLD     qword ptr [EAX+EDX+24]  // Load Data1
  993.        FADD    ST(3),ST                // Sum := Sum + Data1
  994.        FMUL    ST,ST                   // Data1 := Sqr(Data1)
  995. @@3:   FLD     qword ptr [EAX+EDX+16]  // Load Data2
  996.        FADD    ST(4),ST                // Sum := Sum + Data2
  997.        FMUL    ST,ST                   // Data2 := Sqr(Data2)
  998.        FXCH                            // Move Sqr(Data1) into ST(0)
  999.        FADDP   ST(3),ST                // Sqr1 := Sqr1 + Sqr(Data1); Pop Data1
  1000. @@2:   FLD     qword ptr [EAX+EDX+8]   // Load Data3
  1001.        FADD    ST(4),ST                // Sum := Sum + Data3
  1002.        FMUL    ST,ST                   // Data3 := Sqr(Data3)
  1003.        FXCH                            // Move Sqr(Data2) into ST(0)
  1004.        FADDP   ST(3),ST                // Sqr1 := Sqr1 + Sqr(Data2); Pop Data2
  1005. @@1:   FLD     qword ptr [EAX+EDX]     // Load Data4
  1006.        FADD    ST(4),ST                // Sum := Sum + Data4
  1007.        FMUL    ST,ST                   // Sqr(Data4)
  1008.        FXCH                            // Move Sqr(Data3) into ST(0)
  1009.        FADDP   ST(3),ST                // Sqr1 := Sqr1 + Sqr(Data3); Pop Data3
  1010.        SUB     EDX,32
  1011.        JNS     @@4
  1012.        FADD                         // Sqr2 := Sqr2 + Sqr(Data4); Pop Data4
  1013.        POP     ECX
  1014.        FADD                         // Sqr1 := Sqr2 + Sqr1; Pop Sqr2
  1015.        FXCH                         // Move Sum1 into ST(0)
  1016.        MOV     EAX, SumOfSquares
  1017.        FSTP    tbyte ptr [ECX]      // Sum := Sum1; Pop Sum1
  1018.        FSTP    tbyte ptr [EAX]      // SumOfSquares := Sum1; Pop Sum1
  1019.        FWAIT
  1020. end;
  1021.  
  1022. function TotalVariance(const Data: array of Double): Extended;
  1023. var
  1024.   Sum, SumSquares: Extended;
  1025. begin
  1026.   SumsAndSquares(Data, Sum, SumSquares);
  1027.   Result := SumSquares - Sqr(Sum)/(High(Data) - Low(Data) + 1);
  1028. end;
  1029.  
  1030. function Variance(const Data: array of Double): Extended;
  1031. begin
  1032.   Result := TotalVariance(Data) / (High(Data) - Low(Data))
  1033. end;
  1034.  
  1035.  
  1036. { Depreciation functions. }
  1037.  
  1038. function DoubleDecliningBalance(Cost, Salvage: Extended; Life, Period: Integer): Extended;
  1039. { dv := cost * (1 - 2/life)**(period - 1)
  1040.   DDB = (2/life) * dv
  1041.   if DDB > dv - salvage then DDB := dv - salvage
  1042.   if DDB < 0 then DDB := 0
  1043. }
  1044. var
  1045.   DepreciatedVal, Factor: Extended;
  1046. begin
  1047.   Result := 0;
  1048.     if (Period < 1) or (Life < Period) or (Life < 1) or (Cost <= Salvage) then
  1049.     Exit;
  1050.  
  1051.     {depreciate everything in period 1 if life is only one or two periods}
  1052.     if ( Life <= 2 ) then
  1053.   begin
  1054.         if ( Period = 1 ) then
  1055.       DoubleDecliningBalance:=Cost-Salvage
  1056.         else
  1057.             DoubleDecliningBalance:=0; {all depreciation occurred in first period}
  1058.         exit;
  1059.   end;
  1060.   Factor := 2.0 / Life;
  1061.  
  1062.   DepreciatedVal := Cost * IntPower((1.0 - Factor), Period - 1);
  1063.        {DepreciatedVal is Cost-(sum of previous depreciation results)}
  1064.  
  1065.   Result := Factor * DepreciatedVal;
  1066.        {Nominal computed depreciation for this period.  The rest of the
  1067.             function applies limits to this nominal value. }
  1068.  
  1069.     {Only depreciate until total depreciation equals cost-salvage.}
  1070.   if Result > DepreciatedVal - Salvage then
  1071.     Result := DepreciatedVal - Salvage;
  1072.  
  1073.     {No more depreciation after salvage value is reached.  This is mostly a nit.
  1074.      If Result is negative at this point, it's very close to zero.}
  1075.   if Result < 0.0 then
  1076.     Result := 0.0;
  1077. end;
  1078.  
  1079. function SLNDepreciation(Cost, Salvage: Extended; Life: Integer): Extended;
  1080. { Spreads depreciation linearly over life. }
  1081. begin
  1082.   if Life < 1 then ArgError('SLNDepreciation');
  1083.   Result := (Cost - Salvage) / Life
  1084. end;
  1085.  
  1086. function SYDDepreciation(Cost, Salvage: Extended; Life, Period: Integer): Extended;
  1087. { SYD = (cost - salvage) * (life - period + 1) / (life*(life + 1)/2) }
  1088. { Note: life*(life+1)/2 = 1+2+3+...+life "sum of years"
  1089.                 The depreciation factor varies from life/sum_of_years in first period = 1
  1090.                                                                              downto  1/sum_of_years in last period = life.
  1091.                 Total depreciation over life is cost-salvage.}
  1092. var
  1093.   X1, X2: Extended;
  1094. begin
  1095.   Result := 0;
  1096.     if (Period < 1) or (Life < Period) or (Cost <= Salvage) then Exit;
  1097.   X1 := 2 * (Life - Period + 1);
  1098.   X2 := Life * (Life + 1);
  1099.   Result := (Cost - Salvage) * X1 / X2
  1100. end;
  1101.  
  1102. { Discounted cash flow functions. }
  1103.  
  1104. function InternalRateOfReturn(Guess: Extended; const CashFlows: array of Double): Extended;
  1105. {
  1106. Use Newton's method to solve NPV = 0, where NPV is a polynomial in
  1107. x = 1/(1+rate).  Split the coefficients into negative and postive sets:
  1108.   neg + pos = 0, so pos = -neg, so  -neg/pos = 1
  1109. Then solve:
  1110.   log(-neg/pos) = 0
  1111.  
  1112.   Let  t = log(1/(1+r) = -LnXP1(r)
  1113.   then r = exp(-t) - 1
  1114. Iterate on t, then use the last equation to compute r.
  1115. }
  1116. var
  1117.   T, Y: Extended;
  1118.   Poly: TPoly;
  1119.   K, Count: Integer;
  1120.  
  1121.   function ConditionP(const CashFlows: array of Double): Integer;
  1122.   { Guarantees existence and uniqueness of root.  The sign of payments
  1123.     must change exactly once, the net payout must be always > 0 for
  1124.     first portion, then each payment must be >= 0.
  1125.     Returns: 0 if condition not satisfied, > 0 if condition satisfied
  1126.     and this is the index of the first value considered a payback. }
  1127.   var
  1128.     X: Double;
  1129.     I, K: Integer;
  1130.   begin
  1131.     K := High(CashFlows);
  1132.     while (K >= 0) and (CashFlows[K] >= 0.0) do Dec(K);
  1133.     Inc(K);
  1134.     if K > 0 then
  1135.     begin
  1136.       X := 0.0;
  1137.       I := 0;
  1138.       while I < K do begin
  1139.           X := X + CashFlows[I];
  1140.         if X >= 0.0 then
  1141.         begin
  1142.              K := 0;
  1143.             Break
  1144.           end;
  1145.           Inc(I)
  1146.       end
  1147.     end;
  1148.     ConditionP := K
  1149.   end;
  1150.  
  1151. begin
  1152.   InternalRateOfReturn := 0;
  1153.   K := ConditionP(CashFlows);
  1154.   if K < 0 then ArgError('InternalRateOfReturn');
  1155.   if K = 0 then
  1156.   begin
  1157.     if Guess <= -1.0 then ArgError('InternalRateOfReturn');
  1158.     T := -LnXP1(Guess)
  1159.   end else
  1160.     T := 0.0;
  1161.   for Count := 1 to MaxIterations do
  1162.   begin
  1163.     PolyX(CashFlows, Exp(T), Poly);
  1164.     if Poly.Pos <= Poly.Neg then ArgError('InternalRateOfReturn');
  1165.     if (Poly.Neg >= 0.0) or (Poly.Pos <= 0.0) then
  1166.     begin
  1167.       InternalRateOfReturn := -1.0;
  1168.       Exit;
  1169.     end;
  1170.     with Poly do
  1171.       Y := Ln(-Neg / Pos) / (DNeg / Neg - DPos / Pos);
  1172.     T := T - Y;
  1173.     if RelSmall(Y, T) then
  1174.     begin
  1175.       InternalRateOfReturn := Exp(-T) - 1.0;
  1176.       Exit;
  1177.     end
  1178.   end;
  1179.   ArgError('InternalRateOfReturn');
  1180. end;
  1181.  
  1182. function NetPresentValue(Rate: Extended; const CashFlows: array of Double;
  1183.   PaymentTime: TPaymentTime): Extended;
  1184. { Caution: The sign of NPV is reversed from what would be expected for standard
  1185.    cash flows!}
  1186. var
  1187.   rr: Extended;
  1188.   I: Integer;
  1189. begin
  1190.   if Rate <= -1.0 then ArgError('NetPresentValue');
  1191.   rr := 1/(1+Rate);
  1192.   result := 0;
  1193.   for I := High(CashFlows) downto Low(CashFlows) do
  1194.     result := rr * result + CashFlows[I];
  1195.   if PaymentTime = ptEndOfPeriod then result := rr * result;
  1196. end;
  1197.  
  1198. { Annuity functions. }
  1199.  
  1200. {---------------
  1201. From the point of view of A, amounts received by A are positive and
  1202. amounts disbursed by A are negative (e.g. a borrower's loan repayments
  1203. are regarded by the borrower as negative).
  1204.  
  1205. Given interest rate r, number of periods n:
  1206.   compound(r, n) = (1 + r)**n               "Compounding growth factor"
  1207.   annuity(r, n) = (compound(r, n)-1) / r   "Annuity growth factor"
  1208.  
  1209. Given future value fv, periodic payment pmt, present value pv and type
  1210. of payment (start, 1 , or end of period, 0) pmtTime, financial variables satisfy:
  1211.  
  1212.   fv = -pmt*(1 + r*pmtTime)*annuity(r, n) - pv*compound(r, n)
  1213.  
  1214. For fv, pv, pmt:
  1215.  
  1216.   C := compound(r, n)
  1217.   A := (1 + r*pmtTime)*annuity(r, n)
  1218.   Compute both at once in Annuity2.
  1219.  
  1220.   if C > 1E16 then A = C/r, so:
  1221.     fv := meaningless
  1222.     pv := -pmt*(pmtTime+1/r)
  1223.     pmt := -pv*r/(1 + r*pmtTime)
  1224.   else
  1225.     fv := -pmt(1+r*pmtTime)*A - pv*C
  1226.     pv := (-pmt(1+r*pmtTime)*A - fv)/C
  1227.     pmt := (-pv*C-fv)/((1+r*pmtTime)*A)
  1228. ---------------}
  1229.  
  1230. function PaymentParts(Period, NPeriods: Integer; Rate, PresentValue,
  1231.   FutureValue: Extended; PaymentTime: TPaymentTime; var IntPmt: Extended):
  1232.   Extended;
  1233. var
  1234.         Crn:extended; { =Compound(Rate,NPeriods) }
  1235.         Crp:extended; { =Compound(Rate,Period-1) }
  1236.         Arn:extended; { =AnnuityF(Rate,NPeriods) }
  1237.  
  1238. begin
  1239.   if Rate <= -1.0 then ArgError('PaymentParts');
  1240.   Crp:=Compound(Rate,Period-1);
  1241.   Arn:=Annuity2(Rate,NPeriods,PaymentTime,Crn);
  1242.   IntPmt:=(FutureValue*(Crp-1)-PresentValue*(Crn-Crp))/Arn;
  1243.   PaymentParts:=(-FutureValue-PresentValue)*Crp/Arn;
  1244. end;
  1245.  
  1246. function FutureValue(Rate: Extended; NPeriods: Integer; Payment, PresentValue:
  1247.   Extended; PaymentTime: TPaymentTime): Extended;
  1248. var
  1249.   Annuity, CompoundRN: Extended;
  1250. begin
  1251.   if Rate <= -1.0 then ArgError('FutureValue');
  1252.   Annuity := Annuity2(Rate, NPeriods, PaymentTime, CompoundRN);
  1253.   if CompoundRN > 1.0E16 then ArgError('FutureValue');
  1254.   FutureValue := -Payment * Annuity - PresentValue * CompoundRN
  1255. end;
  1256.  
  1257. function InterestPayment(Rate: Extended; Period, NPeriods: Integer; PresentValue,
  1258.   FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  1259. var
  1260.   Crp:extended; { compound(rate,period-1)}
  1261.   Crn:extended; { compound(rate,nperiods)}
  1262.   Arn:extended; { annuityf(rate,nperiods)}
  1263. begin
  1264.   if (Rate <= -1.0)
  1265.     or (Period < 1) or (Period > NPeriods) then ArgError('InterestPayment');
  1266.     Crp:=Compound(Rate,Period-1);
  1267.     Arn:=Annuity2(Rate,Nperiods,PaymentTime,Crn);
  1268.     InterestPayment:=(FutureValue*(Crp-1)-PresentValue*(Crn-Crp))/Arn;
  1269. end;
  1270.  
  1271. function InterestRate(NPeriods: Integer;
  1272.   Payment, PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  1273. {
  1274. Given:
  1275.   First and last payments are non-zero and of opposite signs.
  1276.   Number of periods N >= 2.
  1277. Convert data into cash flow of first, N-1 payments, last with
  1278. first < 0, payment > 0, last > 0.
  1279. Compute the IRR of this cash flow:
  1280.   0 = first + pmt*x + pmt*x**2 + ... + pmt*x**(N-1) + last*x**N
  1281. where x = 1/(1 + rate).
  1282. Substitute x = exp(t) and apply Newton's method to
  1283.   f(t) = log(pmt*x + ... + last*x**N) / -first
  1284. which has a unique root given the above hypotheses.
  1285. }
  1286. var
  1287.   X, Y, Z, First, Pmt, Last, T, ET, EnT, ET1: Extended;
  1288.   Count: Integer;
  1289.   Reverse: Boolean;
  1290.  
  1291.   function LostPrecision(X: Extended): Boolean;
  1292.   asm
  1293.         XOR     EAX, EAX
  1294.         MOV     BX,WORD PTR X+8
  1295.         INC     EAX
  1296.         AND     EBX, $7FF0
  1297.         JZ      @@1
  1298.         CMP     EBX, $7FF0
  1299.         JE      @@1
  1300.         XOR     EAX,EAX
  1301.   @@1:
  1302.   end;
  1303.  
  1304. begin
  1305.   Result := 0;
  1306.   if NPeriods <= 0 then ArgError('InterestRate');
  1307.   Pmt := Payment;
  1308.   if PaymentTime = ptEndOfPeriod then
  1309.   begin
  1310.     X := PresentValue;
  1311.     Y := FutureValue + Payment
  1312.   end
  1313.   else
  1314.   begin
  1315.     X := PresentValue + Payment;
  1316.     Y := FutureValue
  1317.   end;
  1318.   First := X;
  1319.   Last := Y;
  1320.   Reverse := False;
  1321.   if First * Payment > 0.0 then
  1322.   begin
  1323.     Reverse := True;
  1324.     T := First;
  1325.     First := Last;
  1326.     Last := T
  1327.   end;
  1328.   if first > 0.0 then
  1329.   begin
  1330.     First := -First;
  1331.     Pmt := -Pmt;
  1332.     Last := -Last
  1333.   end;
  1334.   if (First = 0.0) or (Last < 0.0) then ArgError('InterestRate');
  1335.   T := 0.0;                     { Guess at solution }
  1336.   for Count := 1 to MaxIterations do
  1337.   begin
  1338.     EnT := Exp(NPeriods * T);
  1339.     if {LostPrecision(EnT)} ent=(ent+1) then
  1340.     begin
  1341.       Result := -Pmt / First;
  1342.       if Reverse then
  1343.         Result := Exp(-LnXP1(Result)) - 1.0;
  1344.       Exit;
  1345.     end;
  1346.     ET := Exp(T);
  1347.     ET1 := ET - 1.0;
  1348.     if ET1 = 0.0 then
  1349.     begin
  1350.       X := NPeriods;
  1351.       Y := X * (X - 1.0) / 2.0
  1352.     end
  1353.     else
  1354.     begin
  1355.       X := ET * (Exp((NPeriods - 1) * T)-1.0) / ET1;
  1356.       Y := (NPeriods * EnT - ET - X * ET) / ET1
  1357.     end;
  1358.     Z := Pmt * X + Last * EnT;
  1359.     Y := Ln(Z / -First) / ((Pmt * Y + Last * NPeriods *EnT) / Z);
  1360.     T := T - Y;
  1361.     if RelSmall(Y, T) then
  1362.     begin
  1363.       if not Reverse then T := -T;
  1364.       InterestRate := Exp(T)-1.0;
  1365.       Exit;
  1366.     end
  1367.   end;
  1368.   ArgError('InterestRate');
  1369. end;
  1370.  
  1371. function NumberOfPeriods(Rate, Payment, PresentValue, FutureValue: Extended;
  1372.   PaymentTime: TPaymentTime): Extended;
  1373.  
  1374. { If Rate = 0 then nper := -(pv + fv) / pmt
  1375.   else cf := pv + pmt * (1 + rate*pmtTime) / rate
  1376.        nper := LnXP1(-(pv + fv) / cf) / LnXP1(rate) }
  1377.  
  1378. var
  1379.   PVRPP: Extended; { =PV*Rate+Payment } {"initial cash flow"}
  1380.   T:     Extended;
  1381.  
  1382. begin
  1383.  
  1384.   if Rate <= -1.0 then ArgError('NumberOfPeriods');
  1385.  
  1386. {whenever both Payment and PaymentTime are given together, the PaymentTime has the effect
  1387.  of modifying the effective Payment by the interest accrued on the Payment}
  1388.  
  1389.   if ( PaymentTime=ptStartOfPeriod ) then
  1390.     Payment:=Payment*(1+Rate);
  1391.  
  1392. {if the payment exactly matches the interest accrued periodically on the
  1393.  presentvalue, then an infinite number of payments are going to be
  1394.  required to effect a change from presentvalue to futurevalue.  The
  1395.  following catches that specific error where payment is exactly equal,
  1396.  but opposite in sign to the interest on the present value.  If PVRPP
  1397.  ("initial cash flow") is simply close to zero, the computation will
  1398.  be numerically unstable, but not as likely to cause an error.}
  1399.  
  1400.   PVRPP:=PresentValue*Rate+Payment;
  1401.   if PVRPP=0 then ArgError('NumberOfPeriods');
  1402.  
  1403.   { 6.1E-5 approx= 2**-14 }
  1404.   if ( ABS(Rate)<6.1E-5 ) then
  1405.     Result:=-(PresentValue+FutureValue)/PVRPP
  1406.   else
  1407.   begin
  1408.  
  1409. {starting with the initial cash flow, each compounding period cash flow
  1410.  should result in the current value approaching the final value.  The
  1411.  following test combines a number of simultaneous conditions to ensure
  1412.  reasonableness of the cashflow before computing the NPER.}
  1413.  
  1414.     T:= -(PresentValue+FutureValue)*Rate/PVRPP;
  1415.     if  T<=-1.0  then ArgError('NumberOfPeriods');
  1416.     Result := LnXP1(T) / LnXP1(Rate)
  1417.   end;
  1418.   NumberOfPeriods:=Result;
  1419. end;
  1420.  
  1421. function Payment(Rate: Extended; NPeriods: Integer; PresentValue, FutureValue:
  1422.   Extended; PaymentTime: TPaymentTime): Extended;
  1423. var
  1424.   Annuity, CompoundRN: Extended;
  1425. begin
  1426.   if Rate <= -1.0 then ArgError('Payment');
  1427.   Annuity := Annuity2(Rate, NPeriods, PaymentTime, CompoundRN);
  1428.   if CompoundRN > 1.0E16 then
  1429.     Payment := -PresentValue * Rate / (1 + Integer(PaymentTime) * Rate)
  1430.   else
  1431.     Payment := (-PresentValue * CompoundRN - FutureValue) / Annuity
  1432. end;
  1433.  
  1434. function PeriodPayment(Rate: Extended; Period, NPeriods: Integer;
  1435.   PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  1436. var
  1437.   Junk: Extended;
  1438. begin
  1439.   if (Rate <= -1.0) or (Period < 1) or (Period > NPeriods) then ArgError('PeriodPayment');
  1440.   PeriodPayment := PaymentParts(Period, NPeriods, Rate, PresentValue,
  1441.        FutureValue, PaymentTime, Junk);
  1442. end;
  1443.  
  1444. function PresentValue(Rate: Extended; NPeriods: Integer; Payment, FutureValue:
  1445.   Extended; PaymentTime: TPaymentTime): Extended;
  1446. var
  1447.   Annuity, CompoundRN: Extended;
  1448. begin
  1449.   if Rate <= -1.0 then ArgError('PresentValue');
  1450.   Annuity := Annuity2(Rate, NPeriods, PaymentTime, CompoundRN);
  1451.   if CompoundRN > 1.0E16 then
  1452.     PresentValue := -(Payment / Rate * Integer(PaymentTime) * Payment)
  1453.   else
  1454.     PresentValue := (-Payment * Annuity - FutureValue) / CompoundRN
  1455. end;
  1456.  
  1457. end.
  1458.