Created
September 10, 2012 08:02
-
-
Save agarie/3689558 to your computer and use it in GitHub Desktop.
Estimating PI through simple geometry and statistics
This file contains hidden or 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
with Ada.Text_IO; | |
with Ada.Float_Text_IO; | |
with Ada.Numerics.Float_Random; | |
use Ada.Text_IO; | |
use Ada.Float_Text_IO; | |
use Ada.Numerics.Float_Random; | |
procedure Pi is | |
N: constant Integer := 500000; -- Number of iterations. | |
Counter_Square, Counter_Circle: Integer := 0; | |
Point_X, Point_Y: Float; | |
Pi: Float; | |
G: Generator; | |
function Belongs_To_Circle (X, Y: Float) return Boolean is | |
begin | |
return X*X + Y*Y <= 0.25; | |
end Belongs_To_Circle; | |
begin | |
for I in 1 .. N loop | |
-- Generate a random point inside the square. | |
Point_X := Random(G) - 0.5; | |
Point_Y := Random(G) - 0.5; | |
-- Verify if the points is inside the circle. | |
if Belongs_To_Circle(Point_X, Point_Y) then | |
-- The point belongs to the circle AND the square. | |
Counter_Circle := Counter_Circle + 1; | |
Counter_Square := Counter_Square + 1; | |
else | |
-- In this case, the point is outside the circle. | |
Counter_Square := Counter_Square + 1; | |
end if; | |
end loop; | |
-- Area of square / area of circle = pi/4. | |
Pi := 4.0 * (Float(Counter_Circle) / Float(Counter_Square)); | |
Put ("The estimated value of PI is: "); | |
Put (Pi); | |
end Pi; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment