How can I raise a number to a power in Delphi?
-
2Try Delphi and the Power Function– RRUZJun 14, 2013 at 22:38
-
7even a simple google search could tell you this.– RBAJun 14, 2013 at 22:39
-
1@Diego. Which Delphi version are you using?– Jack G.Jun 14, 2013 at 23:01
-
1@Diego. Your question doesn't even contain a description of "this math function isn't included".– Jack G.Jun 14, 2013 at 23:05
-
4Even a google search for your exact question title brings up the answer– Jerry DodgeJun 14, 2013 at 23:06
|
Show 2 more comments
1 Answer
in Delphi 4 and later, use the Power function from the math unit. In earlier versions, use the Pow function given below.
{** A power function from Jack Lyle. Said to be more powerful than the
Pow function that comes with Delphi. }
function Power2(Base, Exponent : Double) : Double;
{ raises the base to the exponent }
CONST
cTiny = 1e-15;
VAR
Power : Double; { Value before sign correction }
BEGIN
Power := 0;
{ Deal with the near zero special cases }
IF (Abs(Base) < cTiny) THEN BEGIN
Base := 0.0;
END; { IF }
IF (Abs(Exponent) < cTiny) THEN BEGIN
Exponent := 0.0;
END; { IF }
{ Deal with the exactly zero cases }
IF (Base = 0.0) THEN BEGIN
Power := 0.0;
END; { IF }
IF (Exponent = 0.0) THEN BEGIN
Power := 1.0;
END; { IF }
{ Cover everything else }
IF ((Base < 0) AND (Exponent < 0)) THEN
Power := 1/Exp(-Exponent*Ln(-Base))
ELSE IF ((Base < 0) AND (Exponent >= 0)) THEN
Power := Exp(Exponent*Ln(-Base))
ELSE IF ((Base > 0) AND (Exponent < 0)) THEN
Power := 1/Exp(-Exponent*Ln(Base))
ELSE IF ((Base > 0) AND (Exponent >= 0)) THEN
Power := Exp(Exponent*Ln(Base));
{ Correct the sign }
IF ((Base < 0) AND (Frac(Exponent/2.0) <> 0.0)) THEN
Result := -Power
ELSE
Result := Power;
END; { FUNCTION Pow }
Source:
Read more here
-
6