///////////////////////////////////////////////////////////////////////////
//                                                                       //
// Program file name: Monte.java                                         //
//                                                                       //
// © Tao Pang 2006                                                       //
//                                                                       //
// Last modified: January 18, 2006                                       //
//                                                                       //
// (1) This Java program is part of the book, "An Introduction to        //
//     Computational Physics, 2nd Edition," written by Tao Pang and      //
//     published by Cambridge University Press on January 19, 2006.      //
//                                                                       //
// (2) No warranties, express or implied, are made for this program.     //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

// An example of integration with direct Monte
// Carlo scheme with integrand f(x) = x*x.

import java.lang.*;
import java.util.Random;
public class Monte {
  public static void main(String argv[]) {
    Random r = new Random();
    int n = 1000000;
    double s0 = 0;
    double ds = 0; 
    for (int i=0; i<n; ++i) {
      double x = r.nextDouble();
      double f = x*x;
      s0 += f;
      ds += f*f;
    }
    s0 /= n;
    ds /= n;
    ds = Math.sqrt(Math.abs(ds-s0*s0)/n);
    System.out.println("S = " + s0 + " +- " + ds);
  }
}
