EWG01PDemo/js/fft/complex.js
2025-01-17 13:55:44 +08:00

44 lines
1.3 KiB
JavaScript

//-------------------------------------------------
// Add two complex numbers
//-------------------------------------------------
var complexAdd = function (a, b) {
return [a[0] + b[0], a[1] + b[1]];
};
//-------------------------------------------------
// Subtract two complex numbers
//-------------------------------------------------
var complexSubtract = function (a, b) {
return [a[0] - b[0], a[1] - b[1]];
};
//-------------------------------------------------
// Multiply two complex numbers
//
// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
//-------------------------------------------------
var complexMultiply = function (a, b) {
// console.log(`a: ${a}, b: ${b}`);
return [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
};
//-------------------------------------------------
// Calculate |a + bi|
//
// sqrt(a*a + b*b)
//-------------------------------------------------
var complexMagnitude = function (c) {
// console.log(`c[0]:${c[0]}, c[1]:${c[1]}`);
return Math.sqrt(c[0] * c[0] + c[1] * c[1]);
};
//-------------------------------------------------
// Exports
//-------------------------------------------------
module.exports = {
add: complexAdd,
subtract: complexSubtract,
multiply: complexMultiply,
magnitude: complexMagnitude,
};