From e284b2f571a2b745ce509f9ae28ebf4a23529918 Mon Sep 17 00:00:00 2001 From: Jean Privat Date: Tue, 30 Jun 2015 15:18:54 -0400 Subject: [PATCH] tests: add examples/montecarlo.nit Signed-off-by: Jean Privat --- examples/montecarlo.nit | 43 +++++++++++++++++++++++++++++++++++++++++++ tests/sav/montecarlo.res | 11 +++++++++++ 2 files changed, 54 insertions(+) create mode 100644 examples/montecarlo.nit create mode 100644 tests/sav/montecarlo.res diff --git a/examples/montecarlo.nit b/examples/montecarlo.nit new file mode 100644 index 0000000..f6291ca --- /dev/null +++ b/examples/montecarlo.nit @@ -0,0 +1,43 @@ +# This file is part of NIT ( http://www.nitlanguage.org ). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Approximation of Pi using a Monte Carlo simulation. +# +# This is just an example of basic math and random operations. +module montecarlo + +# Number of iterations +var n = 1000 +if args.not_empty then n = 2 ** args.first.to_i + +# Threshold for output +var j = 1 + +# Number of hits +var h = 0 + +for i in [1..n] do + # Random position in the ([0..1[,[0..1[) square + var x = 1.0.rand + var y = 1.0.rand + + # Hit if in the circle + if x*x + y*y <= 1.0 then h += 1 + + # Print + if i >= j or i == n then + print "i={i} h={h} p={(4.0*h.to_f/i.to_f).to_precision(6)}" + j *= 2 + end +end diff --git a/tests/sav/montecarlo.res b/tests/sav/montecarlo.res new file mode 100644 index 0000000..58ad327 --- /dev/null +++ b/tests/sav/montecarlo.res @@ -0,0 +1,11 @@ +i=1 h=1 p=4.000000 +i=2 h=2 p=4.000000 +i=4 h=3 p=3.000000 +i=8 h=7 p=3.500000 +i=16 h=11 p=2.750000 +i=32 h=19 p=2.375000 +i=64 h=45 p=2.812500 +i=128 h=95 p=2.968750 +i=256 h=197 p=3.078125 +i=512 h=385 p=3.007813 +i=1000 h=765 p=3.060000 -- 1.7.9.5