Skip to content

Instantly share code, notes, and snippets.

@sj14
Last active August 29, 2015 14:00
Show Gist options
  • Save sj14/11407835 to your computer and use it in GitHub Desktop.
Save sj14/11407835 to your computer and use it in GitHub Desktop.
Discrete Fourier Transform (Go)
/*
* By Simon Jürgensmeyer, 2014.
* based on the work of Nayuki Minase:
* http://nayuki.eigenstate.org/page/how-to-implement-the-discrete-fourier-transform
*/
package main
import "fmt"
import "math"
func main() {
var inSlice = []complex128{
complex(1, 0),
complex(2, 0),
complex(3, 0),
complex(4, 0),
complex(5, 0),
complex(9, 0),
complex(7, 0),
complex(5, 0),
complex(3, 0),
complex(1, 0),
}
var result []complex128 = fourier(inSlice)
for _, element := range result {
fmt.Printf("\t %12.8f \t %12.8f \n", real(element), imag(element))
}
}
func fourier(input []complex128) (output []complex128) {
var n int = len(input)
var outSlice []complex128
for i, _ := range input {
var sumReal = 0.0
var sumImag = 0.0
for t, _ := range input {
var angle = 2 * math.Pi * float64(i) * float64(t) / float64(n)
sumReal += real(input[t])*math.Cos(float64(angle)) + imag(input[t])*math.Sin(float64(angle))
sumImag += -real(input[t])*math.Sin(float64(angle)) + imag(input[t])*math.Cos(float64(angle))
}
outSlice = append(outSlice, complex(sumReal, sumImag))
}
return outSlice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment