I came across a surprising behaviour in that I cannot take the square powerof a variable. Ada permits that the square power of the actual value be taken though. Below is my sample code:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO;
with Ada.Float_Text_IO;
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;
procedure Test_power is
testing : constant := -0.11603;
begin
Ada.Text_IO.Put("Works fine with numerical value entered directly: ");
Ada.Long_Float_Text_IO.Put (Item => -0.11603 ** 2.0, Fore => 3, Aft => 5, Exp => 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("This does not work: ");
Ada.Long_Float_Text_IO.Put (Item => testing ** 2.0, Fore => 3, Aft => 5, Exp => 0);
end Test_power;
The outputon the screen is:
Works fine with numerical value entered directly: -0.01346
This does not work:
Execution terminated by unhandled exception
Exception name: ADA.NUMERICS.ARGUMENT_ERROR
Message: a-ngelfu.adb:96 instantiated at a-nlelfu.ads:18
Call stack traceback locations:
0x413ed5 0x42771d 0x427a2a 0x4010b4 0x401146 0x7c817075
The compilation was done using:
GPS 4.4.1 (20091215) hosted on i686-pc-mingw32
GNAT GPL 2010 (20100603)
Two questions:
(a) What am I doing wrong when I take testing ** 2.0 ?
(b) The square of -0.11603 is positive 0.01346. So why I am also getting the negative sign in my first ouput?
After some additional testing:
If I take only positive 0.11603, then output (its square) gives
(a) -0.01346
(b) 0.01346
which can imply that part of the problem is with the negative sign.
Thanks a lot…
The
"**"operator raisesNumerics.Operator_Errorwhen the left operand is negative, or when both operands have the value zero.It’s not unreasonable to expect it to work when the right operand is mathematically an exact integer like
2.0, but for non-integer exponents the mathematical result is a complex number, andAda.Numerics.Generic_Elementary_Functionsdoesn’t treat real numbers that happen to be exact integers as a special case.If all you want to do is square a number, use the built-in
"**"operator with an integer exponent. In other words, change this:to this: