Skip to content

Commit

Permalink
move norm to static method
Browse files Browse the repository at this point in the history
  • Loading branch information
DB Tsai committed Nov 26, 2014
1 parent 0b632e6 commit 9b7cb56
Showing 1 changed file with 41 additions and 41 deletions.
82 changes: 41 additions & 41 deletions mllib/src/main/scala/org/apache/spark/mllib/linalg/Vectors.scala
Original file line number Diff line number Diff line change
Expand Up @@ -92,45 +92,6 @@ sealed trait Vector extends Serializable {
* @return norm in L^p^ space.
*/
private[spark] def norm(p: Double): Double

protected def norm(p: Double, values: Array[Double]): Double = {
require(p >= 1.0)
val size = values.size
if (p == 1) {
var sum = 0.0
var i = 0
while (i < size) {
sum += math.abs(values(i))
i += 1
}
sum
} else if (p == 2) {
var sum = 0.0
var i = 0
while (i < size) {
sum += values(i) * values(i)
i += 1
}
math.sqrt(sum)
} else if (p == Double.PositiveInfinity) {
var max = 0.0
var i = 0
while (i < size) {
val value = math.abs(values(i))
if (value > max) max = value
i += 1
}
max
} else {
var sum = 0.0
var i = 0
while (i < size) {
sum += math.pow(math.abs(values(i)), p)
i += 1
}
math.pow(sum, 1.0 / p)
}
}
}

/**
Expand Down Expand Up @@ -307,6 +268,45 @@ object Vectors {
sys.error("Unsupported Breeze vector type: " + v.getClass.getName)
}
}

private[linalg] def norm(p: Double, values: Array[Double]): Double = {
require(p >= 1.0)
val size = values.size
if (p == 1) {
var sum = 0.0
var i = 0
while (i < size) {
sum += math.abs(values(i))
i += 1
}
sum
} else if (p == 2) {
var sum = 0.0
var i = 0
while (i < size) {
sum += values(i) * values(i)
i += 1
}
math.sqrt(sum)
} else if (p == Double.PositiveInfinity) {
var max = 0.0
var i = 0
while (i < size) {
val value = math.abs(values(i))
if (value > max) max = value
i += 1
}
max
} else {
var sum = 0.0
var i = 0
while (i < size) {
sum += math.pow(math.abs(values(i)), p)
i += 1
}
math.pow(sum, 1.0 / p)
}
}
}

/**
Expand Down Expand Up @@ -340,7 +340,7 @@ class DenseVector(val values: Array[Double]) extends Vector {
}
}

private[spark] override def norm(p: Double): Double = norm(p, values)
private[spark] override def norm(p: Double): Double = Vectors.norm(p, values)
}

/**
Expand Down Expand Up @@ -390,5 +390,5 @@ class SparseVector(
}
}

private[spark] override def norm(p: Double): Double = norm(p, values)
private[spark] override def norm(p: Double): Double = Vectors.norm(p, values)
}

0 comments on commit 9b7cb56

Please sign in to comment.