Skip to content

Instantly share code, notes, and snippets.

@nlw0
Created January 15, 2017 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlw0/a846f9215c7b844c2f0a9b273a1aea19 to your computer and use it in GitHub Desktop.
Save nlw0/a846f9215c7b844c2f0a9b273a1aea19 to your computer and use it in GitHub Desktop.
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