Created
January 15, 2017 01:51
-
-
Save nlw0/a846f9215c7b844c2f0a9b273a1aea19 to your computer and use it in GitHub Desktop.
This file contains 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
import scala.math.sqrt | |
import scala.util.Random | |
trait Vec2d { | |
def x: Double | |
def y: Double | |
def -(that: Point): Point = Point(this.x - that.x, this.y - that.y) | |
def +(that: Point): Point = Point(this.x + that.x, this.y + that.y) | |
def *(that: Point): Double = this.x * that.x + this.y * that.y | |
def cross(that: Point): Double = this.x * that.y - this.y * that.x | |
def *(that: Double): Point = Point(this.x * that, this.y * that) | |
def /(that: Double): Point = Point(this.x / that, this.y / that) | |
def sqnorm = x * x + y * y | |
def norm = sqrt(sqnorm) | |
} | |
case class Point(override val x: Double, override val y: Double) extends Vec2d | |
object Point { | |
def nextGaussian = Point(Random.nextGaussian, Random.nextGaussian) | |
def nextUniform = Point(Random.nextDouble, Random.nextDouble) | |
} | |
case class Line(override val x: Double, override val y: Double) extends Vec2d { | |
def distance(p: Point) = { | |
val lp = Point(x, y) | |
val proj = lp * (lp * p) / lp.sqnorm | |
(proj - lp) * lp / lp.norm | |
} | |
def apply(ix: Double) = { | |
y + x * (x - ix) / y | |
} | |
} | |
object Line { | |
def apply(p: Point): Line = Line(p.x, p.y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment