/complex.go

http://gocomplex.googlecode.com/ · Go · 101 lines · 63 code · 17 blank · 21 comment · 0 complexity · 7f7dd6c7f3e17462081a6b15a6dc0bad MD5 · raw file

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. /* This package implements some basic functionality for
  5. complex numbers.
  6. Add
  7. */
  8. package complex
  9. import "math"
  10. type Complex struct {
  11. real float64;
  12. im float64;
  13. }
  14. func NewComplex(_real, _im float64) *Complex {
  15. c := new(Complex);
  16. c.real = _real;
  17. c.im = _im;
  18. return c;
  19. }
  20. // Returns the absolute value
  21. func Abs(z *Complex) float64 {
  22. sq := (z.real * z.real) + (z.im * z.im);
  23. result := math.Sqrt(sq);
  24. return result;
  25. }
  26. // Returns the conjugate
  27. func Conj(z *Complex) *Complex {
  28. result := NewComplex(z.real, -(z.im));
  29. return result;
  30. }
  31. // Adds another complex to this complex (similar to "+=" operator)
  32. func (c *Complex) AddTo(b *Complex) {
  33. c.real += b.real;
  34. c.im += b.im;
  35. }
  36. // Adds two complex numbers together to make a third complex
  37. func Add(a, b *Complex) *Complex {
  38. c := NewComplex(a.real, a.im);
  39. c.AddTo(b);
  40. return c;
  41. }
  42. // Subtracts another complex from this complex (similar to "-=" operator)
  43. func (c *Complex) SubFrom(b *Complex) {
  44. c.real -= b.real;
  45. c.im -= b.im;
  46. }
  47. // Subtracts one complex from another to make a third complex
  48. func Sub(a, b *Complex) *Complex {
  49. c := NewComplex(a.real, a.im);
  50. c.SubFrom(b);
  51. return c;
  52. }
  53. // Multiplies this complex by another complex (similar to "*=" operator)
  54. func (c *Complex) MultBy(b *Complex) {
  55. re := (c.real * b.real) - (c.im * b.im);
  56. im := (c.real * b.im) + (c.im * b.real);
  57. c.real -= re;
  58. c.im -= im;
  59. }
  60. // Multiplies one complex by another to make a third complex
  61. func Mult(a, b *Complex) *Complex {
  62. re := (a.real * b.real) - (a.im * b.im);
  63. im := (a.real * b.im) + (a.im * b.real);
  64. c := NewComplex(re, im);
  65. return c;
  66. }
  67. // Divides this complex by another complex (similar to "/=" operator)
  68. // TODO
  69. func (c *Complex) DivBy(b *Complex) {
  70. re := (c.real * b.real) - (c.im * b.im);
  71. im := (c.real * b.im) + (c.im * b.real);
  72. c.real -= re;
  73. c.im -= im;
  74. }
  75. // Multiplies one complex by another to make a third complex
  76. // TODO
  77. func Div(a, b *Complex) *Complex {
  78. re := (a.real * b.real) - (a.im * b.im);
  79. im := (a.real * b.im) + (a.im * b.real);
  80. c := NewComplex(re, im);
  81. return c;
  82. }