Skip to content

Instantly share code, notes, and snippets.

@l0rinc
Created December 23, 2016 19:44
Show Gist options
  • Save l0rinc/638185bedc111a5d90b5c85ce66f0113 to your computer and use it in GitHub Desktop.
Save l0rinc/638185bedc111a5d90b5c85ce66f0113 to your computer and use it in GitHub Desktop.
/* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*//* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package tutorial.webapp
import java.lang.Math._
import scala.Double.{MinValue => MinDouble}
import scala.Iterator._
class Equation {
/* bx + a = 0 */
def solve(b: Double, a: Double) = b match {
case 0 ⇒ a match {
case 0 ⇒ iterate(MinDouble)(nextUp)
case _ ⇒ Seq() // inconsistent
}
case _ ⇒ Seq(-a / b)
}
/* cx^2 + bx + a = 0 */
def solve(c: Double, b: Double, a: Double) = c match {
case 0 ⇒ solve(b, a)
case _ ⇒ b match {
case 0 ⇒ Seq(-c / a)
case _ ⇒
a match {
case 0 ⇒ Seq(0, -c / a)
case _ ⇒
val `-b` = -b
val `2a` = 2 * a
val `2c` = 2 * c
val `b²` = b * b
`b²` - `2a` * `2c` match {
case d if d > 0 ⇒
val part = `-b` - copySign(sqrt(d), b) // b ≠ 0
Seq(part / `2a`, `2c` / part)
case d if d == 0 ⇒ Seq(`-b` / `2a`)
case _ ⇒ Seq() // complex roots
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment