Skip to content

Instantly share code, notes, and snippets.

@7shi
Last active December 4, 2022 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7shi/82c4257f9c8550c5e276777cb5fe2ad2 to your computer and use it in GitHub Desktop.
Save 7shi/82c4257f9c8550c5e276777cb5fe2ad2 to your computer and use it in GitHub Desktop.
[JS] Calculating imaginary and quaternionic numbers
function imul(x, y) {
return [x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0]];
}
function cross(x, y) {
return [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[1] * y[2] - x[2] * y[1]];
}
function vdot(x, y) {
return x.reduce((acc, xi, i) => acc + xi * y[i], 0);
}
function vadd(x, y) {
return x.map((a, i) => a + y[i]);
}
function scale(a, v) {
return v.map(x => a * x);
}
function qmul(x, y) {
// (a+x)(b+y)=ab+ay+bx+xy
const imx = x.slice(1, 4);
const imy = y.slice(1, 4);
const imr = vadd(vadd(scale(x[0], imy), scale(y[0], imx)), cross(imx, imy));
return [x[0] * y[0] - vdot(imx, imy)].concat(imr);
}
function qconj(x) {
return [x[0]].concat(scale(-1, x.slice(1, 4)));
}
function qnorm2(x) {
return vdot(x, x);
}
function qinv(x) {
return scale(qnorm2(x), qconj(x));
}
function normv(x) {
return scale(1 / Math.sqrt(vdot(x, x)), x);
}
function qrot(x, th, n) {
const r = [Math.cos(th / 2)].concat(scale(Math.sin(th / 2), normv(n)));
return qmul(qmul(r, x), qconj(r));
}
// qrot([1, 2, 3, 4], Math.PI / 2, [1, 1, 1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment