Created
December 5, 2011 22:50
-
-
Save agemooij/1435771 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object LinearFit2 { | |
case class Point(x: Double = 0.0, y: Double = 0.0) { | |
def +(that: Point): Point = Point(this.x + that.x, this.y + that.y) | |
} | |
implicit def tupleToPoint(tuple: (Double, Double)): Point = Point(tuple._1, tuple._2) | |
def through (points : Point*) : Point = through(points.toList) | |
def through (points : List[Point]) : Point = { | |
val total = points.foldLeft(Point())(_ + _) | |
val (xAverage, yAverage) = (total.x / points.size , total.y / points.size) | |
val Point(squareSumXX, squareSumXY) = points.foldLeft(Point()) { | |
(squareSums: Point, point: Point) => Point( | |
squareSums.x + pow(point.x - xAverage, 2), | |
squareSums.y + (point.x - xAverage) * (point.y - yAverage) | |
) | |
} | |
val b = (squareSumXY / squareSumXX) | |
Point(yAverage - b * xAverage, b) | |
} | |
} | |
class LinearFit2Test extends Specification { | |
import LinearFit2._ | |
"A LinearFit2" should { | |
"fit a slope for points on a straight line" in { | |
LinearFit2 through (Point(0.0, 1.0), Point(1.0, 1.0), Point(2.0, 1.0)) must beEqualTo(Point(1, 0)) | |
LinearFit2 through (Point(0.0, 0.0), Point(1.0, 1.0), Point(2.0, 2.0)) must beEqualTo(Point(0, 1)) | |
} | |
"fit a slope for points not a straight line" in { | |
LinearFit2 through (Point(0.0, 1.0), Point(1.0, 2.0), Point(2.0, 1.0)) must beEqualTo(Point(4.0/3, 0)) | |
LinearFit2 through (Point(0.0, 0.0), Point(1.0, 0.0), Point(1.0, 2.0), Point(2.0, 2.0)) must beEqualTo(Point(0, 1)) | |
} | |
"accept a List as input type" in { | |
LinearFit2 through (List(Point(0.0, 1.0), Point(1.0, 1.0), Point(2.0, 1.0))) must beEqualTo(Point(1, 0)) | |
} | |
"convert input tuples to input Points" in { | |
LinearFit2 through ((0.0, 1.0), (1.0, 1.0), (2.0, 1.0)) must beEqualTo(Point(1, 0)) | |
} | |
"convert output points to output tuples" in { | |
val output: (Double, Double) = LinearFit2 through ((0.0, 1.0), (1.0, 1.0), (2.0, 1.0)) | |
output must beEqualTo((1.0, 0.0)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment