Guest User

Untitled

a guest
Apr 25th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. package main
  2.  
  3. import(
  4. "fmt";
  5. "math";
  6. )
  7.  
  8. type Point interface {
  9. DistanceFromPoint(point Point) float64;
  10. DistanceFromCartesian(x, y float64) float64;
  11. DistanceFromPolar(r, θ float64) float64;
  12. }
  13.  
  14. type cartesian struct { x, y float64 }
  15.  
  16. func (self cartesian) DistanceFromPoint(other Point) float64 {
  17. return other.DistanceFromCartesian(self.x, self.y);
  18. }
  19.  
  20. func (self cartesian) DistanceFromCartesian(x, y float64) float64 {
  21. dx := math.Fabs(self.x - x);
  22. dy := math.Fabs(self.y - y);
  23. return math.Sqrt(dx*dx + dy*dy);
  24. }
  25.  
  26. func (self cartesian) DistanceFromPolar(r, θ float64) float64 {
  27. x := r * math.Cos(θ);
  28. y := r * math.Sin(θ);
  29. return self.DistanceFromCartesian(x, y);
  30. }
  31.  
  32. type polar struct { r, θ float64 }
  33.  
  34. func (self polar) DistanceFromPoint(other Point) float64 {
  35. return other.DistanceFromPolar(self.r, self.θ);
  36. }
  37.  
  38. func (self polar) DistanceFromCartesian(x, y float64) (result float64) {
  39. r := math.Sqrt(x*x + y*y);
  40. θ := math.Atan(y/x);
  41. return self.DistanceFromPolar(r, θ);
  42. }
  43.  
  44. func (self polar) DistanceFromPolar(r, θ float64) float64 {
  45. return math.Sqrt(
  46. (self.r * self.r)
  47. + (r * r)
  48. - (2 * self.r * r * math.Cos(θ - self.θ)));
  49. }
  50.  
  51. func main() {
  52. a := cartesian{1,1};
  53. b := polar{1,math.Pi/2};
  54. fmt.Println(a.DistanceFromPoint(b));
  55. }
Add Comment
Please, Sign In to add comment