Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:26
Show Gist options
  • Select an option

  • Save dacr/09ea0bd0d697c7719676bd461b6ef3c2 to your computer and use it in GitHub Desktop.

Select an option

Save dacr/09ea0bd0d697c7719676bd461b6ef3c2 to your computer and use it in GitHub Desktop.
Compute PI using montecarlo approach, i.e. using a random generator. / published by https://github.com/dacr/code-examples-manager #3cbc2540-3f21-4114-8218-7e461a470bb6/c12e49a86ce6c9111c2b00ce8f9f8f9834f880d0
// summary : Compute PI using montecarlo approach, i.e. using a random generator.
// keywords : scala, scalatest, pi, random, algorithm, montecarlo, math, tailrec, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 3cbc2540-3f21-4114-8218-7e461a470bb6
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "org.scalatest::scalatest:3.2.16"
// ---------------------
import org.scalatest.*, flatspec.*, matchers.*
def monteCarloPI(iterations:Long=10000000L):Double = {
@annotation.tailrec
def worker(in:Long, out:Long, remainingIterations:Long):Double = {
if (remainingIterations==0) 4d*in/(in+out)
else {
val x = Math.random()
val y = Math.random()
if (x * x + y * y > 1) worker(in, out + 1, remainingIterations - 1)
else worker(in + 1, out, remainingIterations - 1)
}
}
worker(0,0,iterations)
}
object pitest extends AnyFlatSpec with should.Matchers {
"pi monte carlo calculus" should "return a precise enough pi value" in {
monteCarloPI() shouldBe 3.14158d +- 0.001d
}
}
pitest.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment