Question

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!

Était-ce utile?

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

Autres conseils

Your problem is a high school maths problem more than a Scala problem. There are always 2 roots in a quadratic equation (your maths is for a quadratic equation). If the b*b-4*a*c term is negative, then the answer is complex (of the form a + i*b) and one should note there are still 2 roots. If this term is zero, there are two roots that have the same value and always real. If the term is positive, you have two distinct real valued roots. Handling complex numbers in Scala can be achieved as shown here.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top