You should put your result in a Set, because:
- There can be multiple results, so it must be some collection
- You don't want to have duplicates and Set elimintates them for you
So something like this should work:
def roots(a : Double, b : Double, c: Double)= {
if (b*b-4.0*a*c >= 0) {
Set(1,-1).map(-b + _ * math.sqrt(b*b-4.0*a*c))
}else{
Set()
}
}
val a = readDouble
val b = readDouble
val c = readDouble
println(roots(a,b,c))
With this function, you can get the following results:
scala> roots(2,3,4)
res4: scala.collection.immutable.Set[_ <: Double] = Set()
scala> roots(-2,3,4)
res5: scala.collection.immutable.Set[_ <: Double] = Set(3.4031242374328485, -9.403124237432849)
scala> roots(2,0,0)
res6: scala.collection.immutable.Set[_ <: Double] = Set(0.0)
For complex numbers, you can use spire. Just change the code above a little bit:
import spire.implicits._
import spire.math._
def roots(a : Complex[Double], b : Complex[Double], c: Complex[Double]) =
Set(1,-1).map(-b + _ * (b*b-4.0*a*c).sqrt)