/complex.go
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 5/* This package implements some basic functionality for 6 complex numbers. 7 8 Add 9 10*/ 11 12package complex 13 14import "math" 15 16type Complex struct { 17 real float64; 18 im float64; 19} 20 21func NewComplex(_real, _im float64) *Complex { 22 c := new(Complex); 23 c.real = _real; 24 c.im = _im; 25 return c; 26} 27 28// Returns the absolute value 29func Abs(z *Complex) float64 { 30 sq := (z.real * z.real) + (z.im * z.im); 31 result := math.Sqrt(sq); 32 return result; 33} 34 35// Returns the conjugate 36func Conj(z *Complex) *Complex { 37 result := NewComplex(z.real, -(z.im)); 38 return result; 39} 40 41// Adds another complex to this complex (similar to "+=" operator) 42func (c *Complex) AddTo(b *Complex) { 43 c.real += b.real; 44 c.im += b.im; 45} 46 47// Adds two complex numbers together to make a third complex 48func Add(a, b *Complex) *Complex { 49 c := NewComplex(a.real, a.im); 50 c.AddTo(b); 51 return c; 52} 53 54// Subtracts another complex from this complex (similar to "-=" operator) 55func (c *Complex) SubFrom(b *Complex) { 56 c.real -= b.real; 57 c.im -= b.im; 58} 59 60// Subtracts one complex from another to make a third complex 61func Sub(a, b *Complex) *Complex { 62 c := NewComplex(a.real, a.im); 63 c.SubFrom(b); 64 return c; 65} 66 67// Multiplies this complex by another complex (similar to "*=" operator) 68func (c *Complex) MultBy(b *Complex) { 69 re := (c.real * b.real) - (c.im * b.im); 70 im := (c.real * b.im) + (c.im * b.real); 71 c.real -= re; 72 c.im -= im; 73} 74 75// Multiplies one complex by another to make a third complex 76func Mult(a, b *Complex) *Complex { 77 re := (a.real * b.real) - (a.im * b.im); 78 im := (a.real * b.im) + (a.im * b.real); 79 c := NewComplex(re, im); 80 return c; 81} 82 83// Divides this complex by another complex (similar to "/=" operator) 84// TODO 85func (c *Complex) DivBy(b *Complex) { 86 re := (c.real * b.real) - (c.im * b.im); 87 im := (c.real * b.im) + (c.im * b.real); 88 c.real -= re; 89 c.im -= im; 90} 91 92// Multiplies one complex by another to make a third complex 93// TODO 94func Div(a, b *Complex) *Complex { 95 re := (a.real * b.real) - (a.im * b.im); 96 im := (a.real * b.im) + (a.im * b.real); 97 c := NewComplex(re, im); 98 return c; 99} 100 101