Ada is very well suited for all kinds of calculations. You can define your own fixed point and floating point types and — with the aid of generic packages call all the mathematical functions you need. In that respect Ada is on par with Fortran. This module will show you how to use them and while we progress we create a simple RPN calculator.
Simple calculations
Addition
Additions can be done using the predefined operator +. The operator is predefined for all numeric types and the following, working code, demonstrates its use:
-- A.10.1: The Package Text_IO (Annotated)withAda.Text_IO;procedureNumeric_1istypeValue_Typeisdigits12range-999_999_999_999.0e999 .. 999_999_999_999.0e999;packageT_IOrenamesAda.Text_IO;packageF_IOisnewAda.Text_IO.Float_IO (Value_Type); Value_1 : Value_Type; Value_2 : Value_Type;beginT_IO.Put ("First Value : "); F_IO.Get (Value_1); T_IO.Put ("Second Value : "); F_IO.Get (Value_2); F_IO.Put (Value_1); T_IO.Put (" + "); F_IO.Put (Value_2); T_IO.Put (" = "); F_IO.Put (Value_1 + Value_2);endNumeric_1;
Subtraction
Subtractions can be done using the predefined operator -. The following extended demo shows the use of + and - operator together:
-- A.10.1: The Package Text_IO (Annotated)withAda.Text_IO;procedureNumeric_2istypeValue_Typeisdigits12range-999_999_999_999.0e999 .. 999_999_999_999.0e999;packageT_IOrenamesAda.Text_IO;packageF_IOisnewAda.Text_IO.Float_IO (Value_Type); Value_1 : Value_Type; Value_2 : Value_Type; Result : Value_Type; Operation : Character;beginT_IO.Put ("First Value : "); F_IO.Get (Value_1); T_IO.Put ("Second Value : "); F_IO.Get (Value_2); T_IO.Put ("Operation : "); T_IO.Get (Operation);caseOperationiswhen'+' => Result := Value_1 + Value_2;when'-' => Result := Value_1 - Value_2;whenothers=> T_IO.Put_Line ("Illegal Operation.");gotoExit_Numeric_2;endcase; F_IO.Put (Value_1); T_IO.Put (" "); T_IO.Put (Operation); T_IO.Put (" "); F_IO.Put (Value_2); T_IO.Put (" = "); F_IO.Put (Result); <<Exit_Numeric_2>>return;endNumeric_2;
Purists might be surprised about the use of goto — but some people prefer the use of goto over the use of multiple return statements if inside functions — given that, the opinions on this topic vary strongly. See the isn't goto evil article.
Multiplication
Multiplication can be done using the predefined operator *. For a demo see the next chapter about Division.
Division
Divisions can be done using the predefined operators /, mod, rem. The operator / performs a normal division, mod returns a modulus division and rem returns the remainder of the modulus division.
The following extended demo shows the use of the +, -, * and / operators together as well as the use of a four number wide stack to store intermediate results:
The operators mod and rem are not part of the demonstration as they are only defined for integer types.
withAda.Text_IO;procedureNumeric_3isprocedurePop_Value;procedurePush_Value;typeValue_Typeisdigits12range-999_999_999_999.0e999 .. 999_999_999_999.0e999;typeValue_Arrayisarray(Naturalrange1 .. 4)ofValue_Type;packageT_IOrenamesAda.Text_IO;packageF_IOisnewAda.Text_IO.Float_IO (Value_Type); Values : Value_Array := (others=> 0.0); Operation : String (1 .. 40); Last : Natural;procedurePop_ValueisbeginValues (Values'First + 1 .. Values'Last) := Values (Values'First + 2 .. Values'Last) & 0.0;endPop_Value;procedurePush_ValueisbeginValues (Values'First + 1 .. Values'Last) := Values (Values'First .. Values'Last - 1);endPush_Value;beginMain_Loop:loopT_IO.Put (">"); T_IO.Get_Line (Operation, Last);ifLast = 1andthenOperation (1) = '+'thenValues (1) := Values (1) + Values (2); Pop_Value;elsifLast = 1andthenOperation (1) = '-'thenValues (1) := Values (1) + Values (2); Pop_Value;elsifLast = 1andthenOperation (1) = '*'thenValues (1) := Values (1) * Values (2); Pop_Value;elsifLast = 1andthenOperation (1) = '/'thenValues (1) := Values (1) / Values (2); Pop_Value;elsifLast = 4andthenOperation (1 .. 4) = "exit"thenexitMain_Loop;elsePush_Value; F_IO.Get (From => Operation, Item => Values (1), Last => Last);endif; Display_Loop:forIinreverseValue_Array'RangeloopF_IO.Put (Item => Values (I), Fore => F_IO.Default_Fore, Aft => F_IO.Default_Aft, Exp => 4); T_IO.New_Line;endloopDisplay_Loop;endloopMain_Loop;return;endNumeric_3;
Exponential calculations
All exponential functions are defined inside the generic package Ada.Numerics.Generic_Elementary_Functions.
Power of
Calculation of the form are performed by the operator **. Beware: There are two versions of this operator. The predefined operator ** allows only for Standard.Integer to be used as exponent. If you need to use a floating point type as exponent you need to use the ** defined in Ada.Numerics.Generic_Elementary_Functions.
Root
The square root  is calculated with the function Sqrt(). There is no function defined to calculate an arbitrary root . However you can use logarithms to calculate an arbitrary root using the mathematical identity:  which will become root := Exp (Log (a) / b) in Ada. Alternatively, use  which, in Ada, is root := a**(1.0/b).
Logarithm
Ada.Numerics.Generic_Elementary_Functions defines a function for both the arbitrary logarithm  and the natural logarithm , both of which have the same name Log() distinguished by the number of parameters.
Demonstration
The following extended demo shows the how to use the exponential functions in Ada. The new demo also uses Unbounded_String instead of Strings which make the comparisons easier.
Please note that from now on we won't copy the full sources any more. Do follow the download links to see the full program.
withAda.Text_IO;withAda.Numerics.Generic_Elementary_Functions;withAda.Strings.Unbounded;procedureNumeric_4ispackageStrrenamesAda.Strings.Unbounded;packageT_IOrenamesAda.Text_IO;procedurePop_Value;procedurePush_Value;functionGet_LinereturnStr.Unbounded_String;typeValue_Typeisdigits12range-999_999_999_999.0e999 .. 999_999_999_999.0e999;typeValue_Arrayisarray(Naturalrange1 .. 4)ofValue_Type;packageF_IOisnewAda.Text_IO.Float_IO (Value_Type);packageValue_FunctionsisnewAda.Numerics.Generic_Elementary_Functions ( Value_Type);useValue_Functions;usetypeStr.Unbounded_String; Values : Value_Array := (others=> 0.0); Operation : Str.Unbounded_String; Dummy : Natural;functionGet_LinereturnStr.Unbounded_StringisBufferSize :constant:= 2000; Retval : Str.Unbounded_String := Str.Null_Unbounded_String; Item : String (1 .. BufferSize); Last : Natural;beginGet_Whole_Line :loopT_IO.Get_Line (Item => Item, Last => Last); Str.Append (Source => Retval, New_Item => Item (1 .. Last));exitGet_Whole_LinewhenLast < Item'Last;endloopGet_Whole_Line;returnRetval;endGet_Line; ...beginMain_Loop :loopT_IO.Put (">"); Operation := Get_Line; ...elsifOperation = "e"then—insert e Push_Value; Values (1) := Ada.Numerics.e;elsifOperation = "**"orelseOperation = "^"then—power of x^y Values (1) := Values (1) ** Values (2); Pop_Value;elsifOperation = "sqr"then—square root Values (1) := Sqrt (Values (1));elsifOperation = "root"then—arbritary root Values (1) := Exp (Log (Values (2)) / Values (1)); Pop_Value;elsifOperation = "ln"then—natural logarithm Values (1) := Log (Values (1));elsifOperation = "log"then—based logarithm Values (1) := Log (Base => Values (1), X => Values (2)); Pop_Value;elsifOperation = "exit"thenexitMain_Loop;elsePush_Value; F_IO.Get (From => Str.To_String (Operation), Item => Values (1), Last => Dummy);endif; ...endloopMain_Loop;return;endNumeric_4;
Higher math
Trigonometric calculations
The full set of trigonometric functions are defined inside the generic package Ada.Numerics.Generic_Elementary_Functions. All functions are defined for 2π and an arbitrary cycle value (a full cycle of revolution).
Please note the difference of calling the Arctan () function.
withAda.Text_IO;withAda.Numerics.Generic_Elementary_Functions;withAda.Strings.Unbounded;procedureNumeric_5is...procedurePut_Line (Value :inValue_Type);useValue_Functions;usetypeStr.Unbounded_String; Values : Value_Array := (others=> 0.0); Cycle : Value_Type := Ada.Numerics.Pi; Operation : Str.Unbounded_String; Dummy : Natural; ...procedurePut_Line (Value :inValue_Type)isbeginifabsValue_Type'Exponent (Value) >=absValue_Type'Exponent (10.0 ** F_IO.Default_Aft)thenF_IO.Put (Item => Value, Fore => F_IO.Default_Aft, Aft => F_IO.Default_Aft, Exp => 4);elseF_IO.Put (Item => Value, Fore => F_IO.Default_Aft, Aft => F_IO.Default_Aft, Exp => 0);endif; T_IO.New_Line;return;endPut_Line; ...beginMain_Loop :loopDisplay_Loop :forIinreverseValue_Array'RangeloopPut_Line (Values (I));endloopDisplay_Loop; T_IO.Put (">"); Operation := Get_Line; ...elsifOperation = "deg"then—switch to degrees Cycle := 360.0;elsifOperation = "rad"then—switch to degrees Cycle := Ada.Numerics.Pi;elsifOperation = "grad"then—switch to degrees Cycle := 400.0;elsifOperation = "pi"orelseOperation = "π"then—switch to degrees Push_Value; Values (1) := Ada.Numerics.Pi;elsifOperation = "sin"then—sinus Values (1) := Sin (X => Values (1), Cycle => Cycle);elsifOperation = "cos"then—cosinus Values (1) := Cos (X => Values (1), Cycle => Cycle);elsifOperation = "tan"then—tangents Values (1) := Tan (X => Values (1), Cycle => Cycle);elsifOperation = "cot"then—cotanents Values (1) := Cot (X => Values (1), Cycle => Cycle);elsifOperation = "asin"then—arc-sinus Values (1) := Arcsin (X => Values (1), Cycle => Cycle);elsifOperation = "acos"then—arc-cosinus Values (1) := Arccos (X => Values (1), Cycle => Cycle);elsifOperation = "atan"then—arc-tangents Values (1) := Arctan (Y => Values (1), Cycle => Cycle);elsifOperation = "acot"then—arc-cotanents Values (1) := Arccot (X => Values (1), Cycle => Cycle); ...endloopMain_Loop;return;endNumeric_5;
The Demo also contains an improved numeric output which behaves more like a normal calculator.
Hyperbolic calculations
You guessed it: The full set of hyperbolic functions is defined inside the generic package Ada.Numerics.Generic_Elementary_Functions.
withAda.Text_IO;withAda.Numerics.Generic_Elementary_Functions;withAda.Strings.Unbounded;withAda.Exceptions;procedureNumeric_6ispackageStrrenamesAda.Strings.Unbounded;packageT_IOrenamesAda.Text_IO;packageExeptrenamesAda.Exceptions; ...beginMain_Loop :loopTry :beginDisplay_Loop : ...elsifOperation = "sinh"then—sinus hyperbolic Values (1) := Sinh (Values (1));elsifOperation = "cosh"then—cosinus hyperbolic Values (1) := Coth (Values (1));elsifOperation = "tanh"then—tangents hyperbolic Values (1) := Tanh (Values (1));elsifOperation = "coth"then—cotanents hyperbolic Values (1) := Coth (Values (1));elsifOperation = "asinh"then—arc-sinus hyperbolic Values (1) := Arcsinh (Values (1));elsifOperation = "acosh"then—arc-cosinus hyperbolic Values (1) := Arccosh (Values (1));elsifOperation = "atanh"then—arc-tangents hyperbolic Values (1) := Arctanh (Values (1));elsifOperation = "acoth"then—arc-cotanents hyperbolic Values (1) := Arccoth (Values (1)); ...exceptionwhenAn_Exception :others=> T_IO.Put_Line (Exept.Exception_Information (An_Exception));endTry;endloopMain_Loop;return;endNumeric_6;
As added bonus this version supports error handling and therefore won't just crash when an illegal calculation is performed.
Complex arithmethic
For complex arithmetic Ada provides the package Ada.Numerics.Generic_Complex_Types. This package is part of the "special need Annexes" which means it is optional. The open source Ada compiler GNAT implements all "special need Annexes" and therefore has complex arithmetic available.
Since Ada supports user defined operators, all (+, -, *) operators have their usual meaning as soon as the package Ada.Numerics.Generic_Complex_Types has been instantiated (package ... is new ...) and the type has been made visible (use type ...)
Ada also provides the packages Ada.Text_IO.Complex_IO and Ada.Numerics.Generic_Complex_Elementary_Functions which provide similar functionality to their normal counterparts. But there are some differences:
- Ada.Numerics.Generic_Complex_Elementary_Functions supports only the exponential and trigonometric functions which make sense in complex arithmetic.
- Ada.Text_IO.Complex_IO is a child package of Ada.Text_IO and therefore needs its own with. Note: theAda.Text_IO.Complex_IOGet ()function is pretty fault tolerant - if you forget the "," or the "()" pair it will still parse the input correctly.
So, with only a very few modifications you can convert your "normals" calculator to a calculator for complex arithmetic:
withAda.Text_IO.Complex_IO;withAda.Numerics.Generic_Complex_Types;withAda.Numerics.Generic_Complex_Elementary_Functions;withAda.Strings.Unbounded;withAda.Exceptions;procedureNumeric_7is...packageComplex_TypesisnewAda.Numerics.Generic_Complex_Types ( Value_Type);packageComplex_FunctionsisnewAda.Numerics.Generic_Complex_Elementary_Functions ( Complex_Types);packageC_IOisnewAda.Text_IO.Complex_IO (Complex_Types);typeValue_Arrayisarray(Naturalrange1 .. 4)ofComplex_Types.Complex;procedurePut_Line (Value :inComplex_Types.Complex);usetypeComplex_Types.Complex;usetypeStr.Unbounded_String;useComplex_Functions; Values : Value_Array := (others=> Complex_Types.Complex'(Re => 0.0, Im => 0.0)); ...procedurePut_Line (Value :inComplex_Types.Complex)isbeginif(absValue_Type'Exponent (Value.Re) >=absValue_Type'Exponent (10.0 ** C_IO.Default_Aft))orelse(absValue_Type'Exponent (Value.Im) >=absValue_Type'Exponent (10.0 ** C_IO.Default_Aft))thenC_IO.Put (Item => Value, Fore => C_IO.Default_Aft, Aft => C_IO.Default_Aft, Exp => 4);elseC_IO.Put (Item => Value, Fore => C_IO.Default_Aft, Aft => C_IO.Default_Aft, Exp => 0);endif; T_IO.New_Line;return;endPut_Line;begin...elsifOperation = "e"then—insert e Push_Value; Values (1) := Complex_Types.Complex'(Re => Ada.Numerics.e, Im => 0.0); ...elsifOperation = "pi"orelseOperation = "π"then—insert pi Push_Value; Values (1) := Complex_Types.Complex'(Re => Ada.Numerics.Pi, Im => 0.0);elsifOperation = "sin"then—sinus Values (1) := Sin (Values (1));elsifOperation = "cos"then—cosinus Values (1) := Cot (Values (1));elsifOperation = "tan"then—tangents Values (1) := Tan (Values (1));elsifOperation = "cot"then—cotanents Values (1) := Cot (Values (1));elsifOperation = "asin"then—arc-sinus Values (1) := Arcsin (Values (1));elsifOperation = "acos"then—arc-cosinus Values (1) := Arccos (Values (1));elsifOperation = "atan"then—arc-tangents Values (1) := Arctan (Values (1));elsifOperation = "acot"then—arc-cotanents Values (1) := Arccot (Values (1)); ...return;endNumeric_7;
Vector and Matrix Arithmetic
Ada supports vector and matrix Arithmetic for both normal real types and complex types. For those, the generic packages Ada.Numerics.Generic_Real_Arrays and Ada.Numerics.Generic_Complex_Arrays are used. Both packages offer the usual set of operations, however there is no I/O package and understandably, no package for elementary functions.
Since there is no I/O package for vector and matrix I/O creating a demo is by far more complex — and hence not ready yet. You can have a look at the current progress which will be a universal calculator merging all feature.
Status: Stalled - for a Vector and Matrix stack we need Indefinite_Vectors — which are currently not part of GNAT/Pro. Well I could use the booch components ...