Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
- }
Add Comment
Please, Sign In to add comment