-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathFFT.test.js
More file actions
59 lines (53 loc) · 1.77 KB
/
FFT.test.js
File metadata and controls
59 lines (53 loc) · 1.77 KB
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
import { multiplyPolynomials, multiplyBigIntegers, convolveReal } from '../FFT'
describe('FFT polynomial multiplication', () => {
it('multiplies small polynomials', () => {
const a = [1, 2, 3] // 1 + 2x + 3x^2
const b = [4, 5] // 4 + 5x
expect(multiplyPolynomials(a, b)).toEqual([4, 13, 22, 15])
})
it('convolution matches naive for random arrays', () => {
const a = [0, 1, 0, 2, 3]
const b = [1, 2, 3]
const conv = convolveReal(a, b)
const naive = []
for (let i = 0; i < a.length + b.length - 1; i++) {
let sum = 0
for (let j = 0; j < a.length; j++) {
const k = i - j
if (k >= 0 && k < b.length) sum += a[j] * b[k]
}
naive.push(sum)
}
expect(conv).toEqual(naive)
})
})
describe('FFT big integer multiplication', () => {
function digitsToBigInt(digs, base = 10) {
// LSD-first digits to BigInt
let s = ''
for (let i = digs.length - 1; i >= 0; i--) s += digs[i].toString(base)
return BigInt(s)
}
function bigIntToDigits(n, base = 10) {
if (n === 0n) return [0]
const digs = []
const b = BigInt(base)
let x = n
while (x > 0n) {
digs.push(Number(x % b))
x /= b
}
return digs
}
it('multiplies large integer arrays (base 10)', () => {
const A = Array.from({ length: 50 }, () => Math.floor(Math.random() * 10))
const B = Array.from({ length: 50 }, () => Math.floor(Math.random() * 10))
const prodDigits = multiplyBigIntegers(A, B, 10)
const prodBigInt = digitsToBigInt(A) * digitsToBigInt(B)
expect(prodDigits).toEqual(bigIntToDigits(prodBigInt))
})
it('handles leading zeros and zero cases', () => {
expect(multiplyBigIntegers([0], [0])).toEqual([0])
expect(multiplyBigIntegers([0, 0, 1], [0, 2])).toEqual([0, 0, 0, 2])
})
})