-2

How can I raise a number to a power in Delphi?

7
  • 2
    Try Delphi and the Power Function
    – RRUZ
    Jun 14, 2013 at 22:38
  • 7
    even a simple google search could tell you this.
    – RBA
    Jun 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
  • 4
    Even a google search for your exact question title brings up the answer Jun 14, 2013 at 23:06

1 Answer 1

11

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

1
  • 6
    @Diego - Add it to your uses clause
    – Shambhala
    Jun 15, 2013 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.