Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save dacr/fb5503656b0de238c59980c98893c11b to your computer and use it in GitHub Desktop.
compute exponential e high precision value / published by https://github.com/dacr/code-examples-manager #cd88fb58-3717-4528-88f1-b3286c541cd2/9eea787ccc4cf535f78d9f90a722e85f623bafdd
// summary : compute exponential e high precision value
// keywords : scala, math, e, math, mathcontext, precision, scale, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : cd88fb58-3717-4528-88f1-b3286c541cd2
// created-on : 2021-02-09T08:58:06Z
// 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"
//> using objectWrapper
// ---------------------
import org.scalatest._
import flatspec._
import matchers._
import scala.math.BigDecimal.RoundingMode
import scala.math._
def e(iter:Int):BigDecimal = {
val from = BigDecimal(1, java.math.MathContext.UNLIMITED)
LazyList
.iterate( (1, from, BigDecimal(1)) ) { case (n, result, fact) =>
val newFact = fact * n
val newResult = result + 1/newFact
(n+1, newResult, newFact)
}.collect {case (n, result, _) if iter == n => result}
.head
}
class ETest extends AnyFlatSpec with should.Matchers {
override def suiteName: String = "FactTest"
"e" should "return the right result" in {
e(20).toDouble shouldBe E
}
it should "give high precision value" in {
val computed = e(2000).setScale(5000, RoundingMode.FLOOR)
info(computed.toString)
}
}
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[ETest].getName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment