How to resolve the algorithm Monte Carlo methods step by step in the Crystal programming language
How to resolve the algorithm Monte Carlo methods step by step in the Crystal 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 Crystal programming language
Source code in the crystal programming language
def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
end
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end
You may also check:How to resolve the algorithm Eban numbers step by step in the Scala programming language
You may also check:How to resolve the algorithm Kolakoski sequence step by step in the zkl programming language
You may also check:How to resolve the algorithm Create a two-dimensional array at runtime step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm Terminal control/Clear the screen step by step in the Batch File programming language
You may also check:How to resolve the algorithm Parallel brute force step by step in the Haskell programming language