Roots of a function: Difference between revisions

Content added Content deleted
(Scala contribution maintained.)
Line 2,432: Line 2,432:


=={{header|Scala}}==
=={{header|Scala}}==
===Imperative version (Ugly, side effects)===
{{improve|Scala}}<!-- Why? This template added in place of direct categorization that failed to give any reason. -->
{{trans|Java}}
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/T63KUsH/0 (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/bh8von94Q1y0tInvEZ3cBQ Scastie (remote JVM)].
<lang Scala>object Roots extends App {
val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x

private def printRoots(f: Double => Double,
lowerBound: Double,
upperBound: Double,
step: Double): Unit = {
val y = f(lowerBound)
var (ox, oy, os) = (lowerBound, y, math.signum(y))

for (x <- lowerBound to upperBound by step) {
val y = f(x)
val s = math.signum(y)
if (s == 0) println(x)
else if (s != os) println(s"~${x - (x - ox) * (y / (y - oy))}")

ox = x
oy = y
os = s
}
}

printRoots(poly, -1.0, 4, 0.002)

}</lang>
===Functional version (Recommended)===
<lang Scala>object RootsOfAFunction extends App {
<lang Scala>object RootsOfAFunction extends App {
def findRoots(fn: Double => Double, start: Double, stop: Double, step: Double, epsilon: Double) = {
def findRoots(fn: Double => Double, start: Double, stop: Double, step: Double, epsilon: Double) = {
Line 2,445: Line 2,473:
println(findRoots(fn, -1.0, 3.0, 0.0001, 0.000000001))
println(findRoots(fn, -1.0, 3.0, 0.0001, 0.000000001))
}</lang>
}</lang>

{{out}}
{{out}}
Vector(-9.381755897326649E-14, 0.9999999999998124, 1.9999999999997022)
Vector(-9.381755897326649E-14, 0.9999999999998124, 1.9999999999997022)