forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fast_fourier_transform.rs
223 lines (202 loc) · 6.53 KB
/
fast_fourier_transform.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use std::ops::{Add, Mul, MulAssign, Sub};
// f64 complex
#[derive(Clone, Copy, Debug)]
pub struct Complex64 {
pub re: f64,
pub im: f64,
}
impl Complex64 {
#[inline]
pub fn new(re: f64, im: f64) -> Self {
Self { re, im }
}
#[inline]
pub fn square_norm(&self) -> f64 {
self.re * self.re + self.im * self.im
}
#[inline]
pub fn norm(&self) -> f64 {
self.square_norm().sqrt()
}
#[inline]
pub fn inverse(&self) -> Complex64 {
let nrm = self.square_norm();
Complex64 {
re: self.re / nrm,
im: -self.im / nrm,
}
}
}
impl Default for Complex64 {
#[inline]
fn default() -> Self {
Self { re: 0.0, im: 0.0 }
}
}
impl Add<Complex64> for Complex64 {
type Output = Complex64;
#[inline]
fn add(self, other: Complex64) -> Complex64 {
Complex64 {
re: self.re + other.re,
im: self.im + other.im,
}
}
}
impl Sub<Complex64> for Complex64 {
type Output = Complex64;
#[inline]
fn sub(self, other: Complex64) -> Complex64 {
Complex64 {
re: self.re - other.re,
im: self.im - other.im,
}
}
}
impl Mul<Complex64> for Complex64 {
type Output = Complex64;
#[inline]
fn mul(self, other: Complex64) -> Complex64 {
Complex64 {
re: self.re * other.re - self.im * other.im,
im: self.re * other.im + self.im * other.re,
}
}
}
impl MulAssign<Complex64> for Complex64 {
#[inline]
fn mul_assign(&mut self, other: Complex64) {
let tmp = self.re * other.im + self.im * other.re;
self.re = self.re * other.re - self.im * other.im;
self.im = tmp;
}
}
pub fn fast_fourier_transform_input_permutation(length: usize) -> Vec<usize> {
let mut result = Vec::new();
result.reserve_exact(length);
for i in 0..length {
result.push(i);
}
let mut reverse = 0_usize;
let mut position = 1_usize;
while position < length {
let mut bit = length >> 1;
while bit & reverse != 0 {
reverse ^= bit;
bit >>= 1;
}
reverse ^= bit;
// This is equivalent to adding 1 to a reversed number
if position < reverse {
// Only swap each element once
result.swap(position, reverse);
}
position += 1;
}
result
}
pub fn fast_fourier_transform(input: &[f64], input_permutation: &[usize]) -> Vec<Complex64> {
let n = input.len();
let mut result = Vec::new();
result.reserve_exact(n);
for position in input_permutation {
result.push(Complex64::new(input[*position], 0.0));
}
let mut segment_length = 1_usize;
while segment_length < n {
segment_length <<= 1;
let angle: f64 = std::f64::consts::TAU / segment_length as f64;
let w_len = Complex64::new(angle.cos(), angle.sin());
for segment_start in (0..n).step_by(segment_length) {
let mut w = Complex64::new(1.0, 0.0);
for position in segment_start..(segment_start + segment_length / 2) {
let a = result[position];
let b = result[position + segment_length / 2] * w;
result[position] = a + b;
result[position + segment_length / 2] = a - b;
w *= w_len;
}
}
}
result
}
pub fn inverse_fast_fourier_transform(
input: &[Complex64],
input_permutation: &[usize],
) -> Vec<f64> {
let n = input.len();
let mut result = Vec::new();
result.reserve_exact(n);
for position in input_permutation {
result.push(input[*position]);
}
let mut segment_length = 1_usize;
while segment_length < n {
segment_length <<= 1;
let angle: f64 = -std::f64::consts::TAU / segment_length as f64;
let w_len = Complex64::new(angle.cos(), angle.sin());
for segment_start in (0..n).step_by(segment_length) {
let mut w = Complex64::new(1.0, 0.0);
for position in segment_start..(segment_start + segment_length / 2) {
let a = result[position];
let b = result[position + segment_length / 2] * w;
result[position] = a + b;
result[position + segment_length / 2] = a - b;
w *= w_len;
}
}
}
let scale = 1.0 / n as f64;
result.iter().map(|x| x.re * scale).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn almost_equal(a: f64, b: f64, epsilon: f64) -> bool {
(a - b).abs() < epsilon
}
const EPSILON: f64 = 1e-6;
#[test]
fn small_polynomial_returns_self() {
let polynomial = vec![1.0f64, 1.0, 0.0, 2.5];
let permutation = fast_fourier_transform_input_permutation(polynomial.len());
let fft = fast_fourier_transform(&polynomial, &permutation);
let ifft = inverse_fast_fourier_transform(&fft, &permutation);
for (x, y) in ifft.iter().zip(polynomial.iter()) {
assert!(almost_equal(*x, *y, EPSILON));
}
}
#[test]
fn square_small_polynomial() {
let mut polynomial = vec![1.0f64, 1.0, 0.0, 2.0];
polynomial.append(&mut vec![0.0; 4]);
let permutation = fast_fourier_transform_input_permutation(polynomial.len());
let mut fft = fast_fourier_transform(&polynomial, &permutation);
fft.iter_mut().for_each(|num| *num *= *num);
let ifft = inverse_fast_fourier_transform(&fft, &permutation);
let expected = vec![1.0, 2.0, 1.0, 4.0, 4.0, 0.0, 4.0, 0.0, 0.0];
for (x, y) in ifft.iter().zip(expected.iter()) {
assert!(almost_equal(*x, *y, EPSILON));
}
}
#[test]
#[ignore]
fn square_big_polynomial() {
// This test case takes ~1050ms on my machine in unoptimized mode,
// but it takes ~70ms in release mode.
let n = 1 << 17; // ~100_000
let mut polynomial = vec![1.0f64; n];
polynomial.append(&mut vec![0.0f64; n]);
let permutation = fast_fourier_transform_input_permutation(polynomial.len());
let mut fft = fast_fourier_transform(&polynomial, &permutation);
fft.iter_mut().for_each(|num| *num *= *num);
let ifft = inverse_fast_fourier_transform(&fft, &permutation);
let mut expected = vec![0.0; n << 1];
for i in 0..((n << 1) - 1) {
expected[i] = std::cmp::min(i + 1, (n << 1) - 1 - i) as f64;
}
for (x, y) in ifft.iter().zip(expected.iter()) {
assert!(almost_equal(*x, *y, EPSILON));
}
}
}