How to resolve the algorithm Monte Carlo methods step by step in the Scala programming language
How to resolve the algorithm Monte Carlo methods step by step in the Scala programming language
Table of Contents
Problem Statement
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be
π
/
4
{\displaystyle \pi /4}
. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately
π
/
4
{\displaystyle \pi /4}
.
Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number
π
{\displaystyle \pi }
is not built-in, we give
π
{\displaystyle \pi }
as a number of digits:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Monte Carlo methods step by step in the Scala programming language
Source code in the scala programming language
object MonteCarlo {
private val random = new scala.util.Random
/** Returns a random number between -1 and 1 */
def nextThrow: Double = (random.nextDouble * 2.0) - 1.0
/** Returns true if the argument point would be 'inside' the unit circle with
* center at the origin, and bounded by a square with side lengths of 2
* units. */
def insideCircle(pt: (Double, Double)): Boolean = pt match {
case (x, y) => (x * x) + (y * y) <= 1.0
}
/** Runs the simulation the specified number of times. Uses the result to
* estimate a value of pi */
def simulate(times: Int): Double = {
val inside = Iterator.tabulate (times) (_ => (nextThrow, nextThrow)) count insideCircle
inside.toDouble / times.toDouble * 4.0
}
def main(args: Array[String]): Unit = {
val sims = Seq(10000, 100000, 1000000, 10000000, 100000000)
sims.foreach { n =>
println(n+" simulations; pi estimation: "+ simulate(n))
}
}
}
You may also check:How to resolve the algorithm MD5 step by step in the S-lang programming language
You may also check:How to resolve the algorithm String length step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the Eiffel programming language
You may also check:How to resolve the algorithm Water collected between towers step by step in the Erlang programming language
You may also check:How to resolve the algorithm Infinity step by step in the Phixmonti programming language