Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Working version, generates all points, correct value of pie, FIXED maths on java:18
- //Add comments for testing (up top) & on how program works (throughout program)
- public class RandomlyCalculatingPie
- {
- public static void main(String args[])
- {
- //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
- int circleCentreX = 0;
- int circleCentreY = 0;
- int liesInCircle = 0;
- double totalPoints = 1000000;
- int squareLength = 2;
- int halfSqLength = squareLength / 2;
- for(int i = 0; i < totalPoints; i++)
- {
- double x = (Math.random() * squareLength)-(halfSqLength);
- double y = (Math.random() * squareLength)-(halfSqLength);
- if(Math.sqrt(Math.pow(x, 2D) + Math.pow(y, 2D)) <= halfSqLength)
- {
- //lies within the circle
- liesInCircle++;
- }
- }
- double estimatePie = (liesInCircle*4 / totalPoints);
- System.out.println("Pie: "+ estimatePie);
- System.out.println(liesInCircle + " points landed in the cirlce.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement