Created
November 25, 2009 19:57
-
-
Save stesla/242987 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
package main | |
import( | |
"fmt"; | |
"math"; | |
) | |
type Point interface { | |
DistanceFromPoint(point Point) float64; | |
DistanceFromCartesian(x, y float64) float64; | |
DistanceFromPolar(r, θ float64) float64; | |
} | |
type cartesian struct { x, y float64 } | |
func (self cartesian) DistanceFromPoint(other Point) float64 { | |
return other.DistanceFromCartesian(self.x, self.y); | |
} | |
func (self cartesian) DistanceFromCartesian(x, y float64) float64 { | |
dx := math.Fabs(self.x - x); | |
dy := math.Fabs(self.y - y); | |
return math.Sqrt(dx*dx + dy*dy); | |
} | |
func (self cartesian) DistanceFromPolar(r, θ float64) float64 { | |
x := r * math.Cos(θ); | |
y := r * math.Sin(θ); | |
return self.DistanceFromCartesian(x, y); | |
} | |
type polar struct { r, θ float64 } | |
func (self polar) DistanceFromPoint(other Point) float64 { | |
return other.DistanceFromPolar(self.r, self.θ); | |
} | |
func (self polar) DistanceFromCartesian(x, y float64) (result float64) { | |
r := math.Sqrt(x*x + y*y); | |
θ := math.Atan(y/x); | |
return self.DistanceFromPolar(r, θ); | |
} | |
func (self polar) DistanceFromPolar(r, θ float64) float64 { | |
return math.Sqrt( | |
(self.r * self.r) | |
+ (r * r) | |
- (2 * self.r * r * math.Cos(θ - self.θ))); | |
} | |
func main() { | |
a := cartesian{1,1}; | |
b := polar{1,math.Pi/2}; | |
fmt.Println(a.DistanceFromPoint(b)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment