Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. //Working version, generates all points, correct value of pie, FIXED maths on java:18
  2. //Add comments for testing (up top) & on how program works (throughout program)
  3.  
  4. public class RandomlyCalculatingPie
  5. {
  6.         public static void main(String args[])
  7.         {          
  8.                 //using a long would be better in the long run but an int can have a max value of 2147M so an integer will do this time
  9.                 int circleCentreX = 0;
  10.                 int circleCentreY = 0;
  11.                 int liesInCircle = 0;
  12.                 double totalPoints = 1000000;
  13.                 int squareLength = 2;
  14.                 int halfSqLength = squareLength / 2;
  15.                 for(int i = 0; i < totalPoints; i++)
  16.                 {
  17.                         double x = (Math.random() * squareLength)-(halfSqLength);
  18.                         double y = (Math.random() * squareLength)-(halfSqLength);
  19.                         if(Math.sqrt(Math.pow(x, 2D) + Math.pow(y, 2D)) <= halfSqLength)
  20.                         {
  21.                                 //lies within the circle
  22.                                 liesInCircle++;
  23.                         }
  24.                 }
  25.                 double estimatePie = (liesInCircle*4 / totalPoints);
  26.                 System.out.println("Pie: "+ estimatePie);
  27.                 System.out.println(liesInCircle + " points landed in the cirlce.");
  28.                
  29.         }
  30.  
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement