Skip to content

Instantly share code, notes, and snippets.

@paplorinc
Created December 23, 2016 20:04
Show Gist options
  • Save paplorinc/97b5ed132746b4b2e69d19b13323f710 to your computer and use it in GitHub Desktop.
Save paplorinc/97b5ed132746b4b2e69d19b13323f710 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, a) match {
case (0, 0) ⇒ iterate(MinDouble)(nextUp)
case (0, _) ⇒ Seq() // inconsistent
case _ ⇒ Seq(-a / b)
}
/* cx^2 + bx + a = 0 */
def solve(c: Double, b: Double, a: Double) = (c, b, a) match {
case (0, _, _) ⇒ solve(b, a)
case (_, 0, _) ⇒ Seq(-a / c)
case (_, _, 0) ⇒ Seq(0, -b / c)
case _ ⇒
val `-b` = -b
val `b²` = b * b
val `2a` = 2 * a
val `2c` = 2 * c
`b²` - `2c` * `2a` match {
case d if d > 0 ⇒ val part = `-b` - copySign(sqrt(d), b) // b ≠ 0
Seq(part / `2c`, `2a` / part)
case d if d == 0 ⇒ Seq(`-b` / `2c`)
case _ ⇒ Seq() // complex roots
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment