Search code examples
scalamathcomplex-numbersnegative-numberquadratic

SCALA - Computing Quandratics and Getting Complex numbers


Just a quick question, I have a scala code which finds the roots of a quadratic equation. The problem I am having is printing out multiple answers and getting answers with complex numbers.

PS: I am in the first few weeks of my Scala course so I only know the bare basics.

val a = readDouble
val b = readDouble
val c = readDouble
if(b*b-4.*a*c > 0) //I have this to deal with the negatives :( {
val root1 = (-b + math.sqrt(b*b-4.*a*c)) / (2*a)
val root2 = (-b - math.sqrt(b*b-4.*a*c)) / (2*a)
println(root1 + " " root2)
}
else 
println("No root")

Thanks friend!


Solution

  • 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)