Question

I have the following code for computing the Euclidean distance:

distanceBetween(first:(Double,Double), second:(Double,Double)): Double = {
   math.sqrt((first._1 - second._1) + (first._2 - second._2)) //distance formula
}

When I run it in the Scala interpreter, I am getting this result:

distanceBetween((0.0,0.0),(20.0,20.0))

res0: Double = NaN

Can anyone shed light as to why I am getting this result?

Edit:

Per Patashu and ntalbs, the correct code for the Euclidean distance between two points is:

distanceBetween(first:(Double,Double), second:(Double,Double)): Double = {
   scala.math.sqrt( scala.math.pow(second._1 - first._1, 2) + scala.math.pow(second._2 - first._2, 2) ) //distance formula
}
Was it helpful?

Solution

You forgot to wrap absolute value around the subtractions. sqrt of a negative number is NaN.

EDIT: I am dumb. You probably meant to do euclidean distance, which is sqrt((x2-x1)^2+(y2-y1)^2), squared instead of abs.

(If you meant to do taxicab distance, aka distance if you can only move horizontally and vertically, that's abs(x2-x1)+abs(y2-y1).)

OTHER TIPS

Perhaps you want to check the formula for calculating distance between two points in 2D:

d = sqrt((x2-x1)^2 + (y2-y1)^2)

With this formula, inside the sqrt() never be negative number. So the code should be like the following:

def distanceBetween(first:(Double,Double), second:(Double,Double)): Double = {
  val dx = second._1 - first._1
  val dy = second._2 - first._2
  math.sqrt(dx*dx + dy*dy)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top