简体   繁体   中英

Error when using Power in Delphi

I have the following function in my program and it is giving me an EInvalidOp (Invalid Floating Point Operation):

function TMyProgram.GetVal(A, B, C, D, E: double): double;

begin

  Result := A/Power((C - D)/(D - B), 1/E);

end;

The values of the parameters are:

A: 320.068, B: 84.46, C: 91.632, D: 24.15, E: 11

Excel gives me a result of -316.815, but Delphi is giving me an error when I execute this function.

I did a bit more research. The problem is raising a negative base to a fractional exponent. In your particular case you can use mathematical identity to get around it by doing the following:

function TMyProgram.GetVal(A, B, C, D: Double; E: Integer): double;
begin
  if Odd(E) and ((C - D)/(D - B) < 0) then
    Result := A/-Power(Abs((C - D)/(D - B)), 1/E)
  else
    Result := A/Power((C - D)/(D - B), 1/E);
end;

This only works when E is an odd number.

-316.81520613

Thats what i get with the power2 function by Jack Lyle.

look here for full code power2

{** 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 }
    ... // see the link to full code

  END; { FUNCTION Pow }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM