Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/fb5503656b0de238c59980c98893c11b to your computer and use it in GitHub Desktop.
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/b5b8ae7e39fc80648c15b9861c223e78a37f3579
// summary : compute exponential e high precision value
// keywords : scala, math, e, math, mathcontext, precision, scale, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.3.0"
//> 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