fft

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fft computes discrete Fourier transforms of any length, in O(n log n), using only the standard library. It's checked against scipy.fft and MATLAB, which the tables in docs/accuracy.md measure.

y, err := fft.ForwardReal(x)
f, err := fft.RealFreq(len(x), 1/fs) // the frequency of each bin, in Hz

Functions

tukey          SciPy                    MATLAB
Forward        fft                      fft
Inverse        ifft                     ifft
ForwardReal    rfft                     fft, its first n/2 + 1 bins
InverseReal    irfft                    ifft(x, n, 'symmetric')
Freq           fftfreq
RealFreq       rfftfreq
Shift          fftshift                 fftshift
InverseShift   ifftshift                ifftshift
FastLength     next_fast_len(n, real=True)

Options apply to every transform:

  • NormBackward, the default, NormOrtho and NormForward choose where the 1/n scaling goes, same as SciPy's norm
  • N truncates or zero-pads the input first, same as SciPy's n and MATLAB's fft(x, n)

Conventions

Every function is stateless: a new slice comes back, inputs are never modified, and all functions are safe for concurrent use. Invalid input returns an error wrapping ErrInvalidLength, ErrSignalTooShort, ErrInvalidParameter or ErrInvalidOption, so check for one with errors.Is.

A NaN or infinite sample is never an error: A transform mixes every sample into every bin, so it makes every bin NaN. A NaN or infinite parameter, such as Freq's d, returns ErrInvalidParameter.

Where tukey differs

  • the names read after the package, so fft.Forward rather than fft.FFT
  • InverseReal needs its length, as n/2 + 1 bins come from both an even and an odd length
  • Freq lists the upper half of the bins as negative frequencies, same as SciPy, where MATLAB's usual (0:n-1)*fs/n lists them above Nyquist
  • FastLength allows factors of 2, 3 and 5 only, where SciPy's next_fast_len also allows 7 and 11
  • an empty input without N is ErrSignalTooShort, same as SciPy

Performance

Every length is O(n log n). Powers of two use iterative radix-2 Cooley-Tukey, other lengths recursive mixed radix with dedicated butterflies for 2, 3, 4 and 5, and primes above 13 Bluestein's algorithm. Lengths with only 2, 3 and 5 as factors are the fastest, so zero-pad to FastLength when any length will do. A real transform of even length costs about half a complex one. Twiddle factors are reduced to an eighth of a turn exactly, so quarter and half turns are exact.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidLength is a length that's wrong in itself.
	ErrInvalidLength = errors.New("fft: invalid length")
	// ErrSignalTooShort is an input with too few samples, including none.
	ErrSignalTooShort = errors.New("fft: signal too short")
	// ErrInvalidParameter is a value outside its domain.
	ErrInvalidParameter = errors.New("fft: invalid parameter")
	// ErrInvalidOption is an option that's unknown or doesn't apply.
	ErrInvalidOption = errors.New("fft: invalid option")
)

Errors returned for invalid input. Each is wrapped with the detail of what was wrong, so check for one with errors.Is. They mean the same in every tukey package.

Functions

func FastLength added in v0.7.0

func FastLength(n int) (length int)

FastLength returns the smallest length of at least n whose only prime factors are 2, 3 and 5, the lengths tukey's transforms are fastest at. Zero-pad to it when any length of at least n will do, e.g. for a correlation:

y, err := fft.Forward(x, fft.N(fft.FastLength(len(x))))

Units: n and length are numbers of samples

Equivalent to:

  • scipy.fft.next_fast_len(n, real=True), whose default also allows factors of 7 and 11
  • MATLAB has none

func Forward

func Forward(x []complex128, opts ...Option) (y []complex128, err error)

Forward returns the discrete Fourier transform of x, n = len(x) bins:

y[k] = Σ x[j]·e^(-2πi·jk/n), for k = 0, 1, ..., n-1

scaled as the Norm options say, unscaled by default. Bin k is at frequency k/n cycles per sample, and Freq gives each bin's frequency.

y, err := fft.Forward(x)

Units: same as x

Returns:

  • ErrSignalTooShort for an empty x without N.
  • ErrInvalidLength for an N below 1.

Equivalent to:

  • scipy.fft.fft(x)
  • MATLAB fft(x)

func ForwardReal

func ForwardReal(x []float64, opts ...Option) (y []complex128, err error)

ForwardReal returns the discrete Fourier transform of the real signal x, keeping only its n/2 + 1 non-negative frequency bins. A real signal's spectrum is Hermitian, X[n-k] = conj(X[k]), so the other bins add nothing. The DC bin, and the Nyquist bin when n is even, are real, with imaginary parts exactly 0. An even n costs about half a complex transform of the same length.

y, err := fft.ForwardReal(x)
f, err := fft.RealFreq(len(x), 1/fs) // the frequency of each bin, in Hz

Units: same as x

Returns:

  • ErrSignalTooShort for an empty x without N.
  • ErrInvalidLength for an N below 1.

Equivalent to:

  • scipy.fft.rfft(x)
  • MATLAB fft(x), whose first n/2 + 1 bins these are
Example
package main

import (
	"fmt"
	"log"
	"math/cmplx"

	"github.com/cxd309/tukey/fft"
	"github.com/cxd309/tukey/waveform"
)

func main() {
	// one second of a 50 Hz sine, sampled at 1 kHz
	const fs, n = 1000.0, 1000
	t, err := waveform.Timebase(n, fs)
	if err != nil {
		log.Fatal(err)
	}
	x, err := waveform.Tone(t, 50, waveform.Phase(-90))
	if err != nil {
		log.Fatal(err)
	}

	spectrum, err := fft.ForwardReal(x)
	if err != nil {
		log.Fatal(err)
	}
	freqs, err := fft.RealFreq(n, 1/fs) // d = 1/fs gives Hz
	if err != nil {
		log.Fatal(err)
	}

	peak := 0
	for k := range spectrum {
		if cmplx.Abs(spectrum[k]) > cmplx.Abs(spectrum[peak]) {
			peak = k
		}
	}
	fmt.Printf("peak at %.0f Hz\n", freqs[peak])
}
Output:
peak at 50 Hz

func Freq

func Freq(n int, d float64) (f []float64, err error)

Freq returns the frequency of each of Forward's n bins, for samples d apart: 0, 1/(n·d), 2/(n·d), ... up to the highest positive frequency, then the negative frequencies, from the most negative up. For even n the Nyquist bin is listed as negative.

f, err := fft.Freq(8, 1.0/8) // [0 1 2 3 -4 -3 -2 -1]

Units:

  • d is the time between samples, e.g. 1/fs in seconds
  • f is in cycles per unit of d, so Hz for d in seconds, and cycles per sample for d = 1

Returns:

  • ErrInvalidLength for a negative n.
  • ErrInvalidParameter for a d that isn't positive and finite.

Equivalent to:

  • scipy.fft.fftfreq(n, d)
  • MATLAB ((0:n-1) - n*((0:n-1) >= ceil(n/2)))/(n*d), as it has no fftfreq

func Inverse

func Inverse(x []complex128, opts ...Option) (y []complex128, err error)

Inverse returns the inverse discrete Fourier transform of x, n = len(x) samples:

y[j] = (1/n)·Σ x[k]·e^(+2πi·jk/n), for j = 0, 1, ..., n-1

so Inverse(Forward(x)) recovers x. The Norm options move the 1/n.

Units: same as x

Returns:

  • ErrSignalTooShort for an empty x without N.
  • ErrInvalidLength for an N below 1.

Equivalent to:

  • scipy.fft.ifft(x)
  • MATLAB ifft(x)

func InverseReal

func InverseReal(x []complex128, n int, opts ...Option) (y []float64, err error)

InverseReal returns the real signal of length n whose non-negative frequency bins are x, same as ForwardReal gives, so InverseReal(ForwardReal(x), len(x)) recovers x. n must be given, as n/2 + 1 bins come from both an even and an odd length. The first n/2 + 1 values of x are used, zero-padded if x is shorter. The imaginary parts of the DC bin, and of the Nyquist bin when n is even, are ignored.

Units: same as x

Returns:

  • ErrInvalidLength for an n below 1.
  • ErrInvalidOption for N, as n is InverseReal's length.

Equivalent to:

  • scipy.fft.irfft(x, n=n)
  • MATLAB ifft(X, 'symmetric'), from the full spectrum X

func InverseShift

func InverseShift[T any](x []T) (y []T)

InverseShift undoes Shift, putting zero frequency back first. For an even length it's the same as Shift, and for an odd length it isn't.

Units: same as x

Equivalent to:

  • scipy.fft.ifftshift(x)
  • MATLAB ifftshift(x)

func RealFreq

func RealFreq(n int, d float64) (f []float64, err error)

RealFreq returns the frequency of each of ForwardReal's n/2 + 1 bins, for samples d apart: 0, 1/(n·d), 2/(n·d), ... up to Nyquist when n is even.

f, err := fft.RealFreq(len(x), 1/fs) // in Hz

Units:

  • d is the time between samples, e.g. 1/fs in seconds
  • f is in cycles per unit of d, so Hz for d in seconds, and cycles per sample for d = 1

Returns:

  • ErrInvalidLength for a negative n.
  • ErrInvalidParameter for a d that isn't positive and finite.

Equivalent to:

  • scipy.fft.rfftfreq(n, d)
  • MATLAB (0:floor(n/2))/(n*d)

func Shift

func Shift[T any](x []T) (y []T)

Shift reorders a spectrum, or its frequencies from Freq, so zero frequency is in the centre: the negative frequencies first, then the non-negative. InverseShift undoes it.

fft.Shift([]float64{0, 1, 2, 3, -4, -3, -2, -1}) // [-4 -3 -2 -1 0 1 2 3]

Units: same as x

Equivalent to:

  • scipy.fft.fftshift(x)
  • MATLAB fftshift(x)
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/fft"
)

func main() {
	// Forward's bins run from 0 up, then the negative frequencies,
	// and Shift puts them in ascending order, with 0 in the centre
	freqs, err := fft.Freq(8, 1.0/8)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(freqs)
	fmt.Println(fft.Shift(freqs))
}
Output:
[0 1 2 3 -4 -3 -2 -1]
[-4 -3 -2 -1 0 1 2 3]

Types

type Option

type Option func(*config)

Option configures a transform: NormBackward, NormOrtho, NormForward or N.

func N

func N(n int) (option Option)

N sets the transform length, truncating or zero-padding the input to n samples first. InverseReal doesn't take it, as its length is its n argument.

Units: n is a number of samples

Equivalent to:

  • scipy.fft.fft(x, n)
  • MATLAB fft(x, n)

func NormBackward

func NormBackward() (option Option)

NormBackward leaves the forward transform unscaled and scales the inverse by 1/n. It's the default.

Equivalent to:

  • scipy.fft's norm="backward", its default
  • MATLAB fft and ifft, which have no other

func NormForward

func NormForward() (option Option)

NormForward scales the forward transform by 1/n and leaves the inverse unscaled, so the DC bin is the signal's mean.

Equivalent to:

  • scipy.fft's norm="forward"
  • MATLAB fft(x)/n

func NormOrtho

func NormOrtho() (option Option)

NormOrtho scales both transforms by 1/√n, so they're unitary and the signal's energy is the same in both domains.

Equivalent to:

  • scipy.fft's norm="ortho"
  • MATLAB fft(x)/sqrt(n)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL