Database Reference
In-Depth Information
How to do it…
We'll implement the Monte Carlo simulation without type hints, benchmark it, and then
reimplement it with type hints to see whether we can get better performance.
1.
The simulation itself places n random points in the unit square and tests how many
of them fall within the upper-right quadrant of a circle centered at 0, 0. The ratio of
those that fall within the circle, multiplied by 4, should approximate the value of pi:
(defn mc-pi [n]
(let [in-circle (->> (repeatedly n rand-point)
(map center-dist)
(filter #(<= % 1.0))
count)]
(* 4.0 (/ in-circle n))))
2.
If we benchmark the existing implementation with Criterium, it will give us something
to shoot for. This shows us that the average runtime is 45.7 milliseconds:
user=> (bench (mc-pi 100000))
WARNING: Final GC required 1.476534955514225 % of runtime
Evaluation count : 1320 in 60 samples of 22 calls.
Execution time mean : 45.774244 ms
Execution time std-deviation : 621.709776 µs
Execution time lower quantile : 44.878862 ms ( 2.5%)
Execution time upper quantile : 46.787552 ms (97.5%)
Overhead used : 1.780493 ns
Found 3 outliers in 60 samples (5.0000 %)
low-severe 2 (3.3333 %)
low-mild 1 (1.6667 %)
Variance from outliers : 1.6389 % Variance is slightly inflated
by outliers
nil
3.
Now, we'll add casts for the primitive doubles in center-dist and add type hint
metadata for the return type too:
(defn center-dist-hint
( ^double [[x y]]
(Math/sqrt (+ (Math/pow (double x) (double 2.0))
(Math/pow (double y)
(double 2.0))))))
 
Search WWH ::




Custom Search