title: Monte Carlo calculation of Pi in Scala
body: <p>Suppose I would like to calculate Pi with Monte Carlo simulation as an exercise.</p>
  
  <p>I am writing a function, which picks a point in a square <code>(0, 1), (1, 0)</code> at random and tests if the point is inside the circle.</p>
  
  <pre><code>import scala.math._
  import scala.util.Random
  
  def circleTest() = {
    val (x, y) = (Random.nextDouble, Random.nextDouble)
    sqrt(x*x + y*y) &lt;= 1
  }
  </code></pre>
  
  <p>Then I am writing a function, which takes as arguments the test function and the number of trials and returns the fraction of the trials in which the test was found to be true.</p>
  
  <pre><code>def monteCarlo(trials: Int, test: () =&gt; Boolean) =
    (1 to trials).map(_ =&gt; if (test()) 1 else 0).sum * 1.0 / trials
  </code></pre>
  
  <p>... and I can calculate Pi</p>
  
  <pre><code>monteCarlo(100000, circleTest) * 4
  </code></pre>
  
  <p>Now I wonder if <code>monteCarlo</code> function can be improved. How would you write <code>monteCarlo</code> efficient and readable ?</p>
  
  <p>For example, since the number of trials is large is it worth using a <code>view</code> or <code>iterator</code> instead of <code>Range(1, trials)</code> and <code>reduce</code> instead of <code>map</code> and <code>sum</code> ? </p>