Created
August 1, 2017 12:36
-
-
Save fsmunoz/6e8c24403fed5a54df019d6c768f1096 to your computer and use it in GitHub Desktop.
Rational approximation in Ada
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Approximates pi using a naïve algorithm as per Brian | |
-- Hayes' http://bit-player.org/2017/approximately-yours | |
-- | |
-- Author: Frederico Munoz <[email protected]> | |
-- Date: Aug 2017 | |
pragma License (GPL); | |
with Ada.Text_IO; | |
with Ada.Long_Float_Text_IO; | |
with Ada.Numerics; | |
-- Approximates pi | |
procedure Approximate is | |
package T_IO renames Ada.Text_IO; | |
package I_IO is new Ada.Text_IO.Integer_IO (Integer); | |
package F_IO is new Ada.Text_IO.Float_IO (Long_Float); | |
T, least_Error,err,merit: Long_Float; | |
dmax, d, n: Integer; | |
begin | |
-- These are hardcoded but can easily be changed | |
T := Ada.Numerics.Pi; --3.141592920353982520964564173482358455657958984375; | |
dmax := 1000000000; | |
-- Additional initialisations | |
d := 1; | |
least_Error := T; | |
while d <= dmax and least_Error > 0.0 loop | |
n := Integer(Long_Float(d) * T); | |
err := abs(T - Long_Float(n)/Long_Float(d)) / T; | |
merit := Long_Float(1) / ((Long_Float(n)**2 + Long_Float(d)**1)**(1/2) * err); | |
if err < least_Error then | |
T_IO.Put_Line (Integer'Image(n) & " / " & Integer'Image(d) & | |
" = " & Long_Float'Image(Long_Float(n)/Long_Float(d)) & | |
" error = " & Long_Float'Image(err) & | |
" merit = " & Long_Float'Image(merit)); | |
least_Error := err; | |
end if; | |
d := d + 1; | |
end loop; | |
end Approximate; |
Author
fsmunoz
commented
Aug 1, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment