Last active
December 4, 2022 05:43
-
-
Save 7shi/82c4257f9c8550c5e276777cb5fe2ad2 to your computer and use it in GitHub Desktop.
[JS] Calculating imaginary and quaternionic numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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