

That means it can return any values between 0 and 1, including 0. but not including 1.
public class Random1 { public static void main(String[] args) { for ( int i = 0 ; i < 10; i++ ) { System.out.println( Math.random() ); // Print a random number } } } 
How to run the program:

Example: Monte Carlo experiment




We will now design a Monte Carlo experiment that can be used to find an estimate for π.
Facts:




Probability [ dart hits yellow portion ] = Area of the quarter circle = π/4 

We can use a Monte Carlo Method (simulating throwing darts) to estimate this probability of success !
int i; int nThrows = 0; int nSuccess = 0; /* ============================== Throw a large number of darts ============================== */ for (i = 0; i < aLargeNumber; i++) { "Throw a dart"; nThrows++; if ( "dart lands inside quarter circle" ) nSuccess++; } /* ================================================================= Estimate the probability of a dart landing inside quarter circle ================================================================== */ System.out.println("Pi/4 = " + (double)nSuccess/(double)nThrows ); 


public class ComputePi1 { public static void main(String[] args) { int i; int nThrows = 0; int nSuccess = 0; double x, y; for (i = 0; i < 1000000 ; i++) { x = Math.random(); // Throw a dart y = Math.random(); nThrows++; if ( x*x + y*y <= 1 ) nSuccess++; } System.out.println("Pi/4 = " + (double)nSuccess/(double)nThrows ); System.out.println("Pi = " + 4*(double)nSuccess/(double)nThrows ); } } 
Output:
Pi/4 = 0.785784 Pi = 3.143136 
How to run the program:
