Add math.frexp and math.ldexp and tests
Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
@@ -95,6 +95,33 @@ export const mathApi = new LuaTable({
|
||||
return new LuaMultiRes([int, frac]);
|
||||
}),
|
||||
|
||||
// Returns m and e such that x = m * 2^e, 0.5 <= |m| < 1 (or m=0 when x=0).
|
||||
// e is an integer. Mirrors C99/Lua.
|
||||
// Special cases: frexp(0) = (0, 0); frexp(+-inf/nan) = (x, 0).
|
||||
frexp: new LuaBuiltinFunction((_sf, x: number) => {
|
||||
const xn = untagNumber(x);
|
||||
if (xn === 0 || !isFinite(xn) || isNaN(xn)) {
|
||||
return new LuaMultiRes([xn, 0]);
|
||||
}
|
||||
const abs = Math.abs(xn);
|
||||
let e = Math.floor(Math.log2(abs)) + 1;
|
||||
let m = xn / Math.pow(2, e);
|
||||
if (Math.abs(m) >= 1.0) {
|
||||
e += 1;
|
||||
m /= 2;
|
||||
}
|
||||
if (Math.abs(m) < 0.5) {
|
||||
e -= 1;
|
||||
m *= 2;
|
||||
}
|
||||
return new LuaMultiRes([m, e]);
|
||||
}),
|
||||
|
||||
// Returns m * 2^e (the inverse of frexp). Mirrors C99/Lua.
|
||||
ldexp: new LuaBuiltinFunction((_sf, m: number, e: number) =>
|
||||
untagNumber(m) * Math.pow(2, untagNumber(e))
|
||||
),
|
||||
|
||||
// Power and logarithms
|
||||
exp: new LuaBuiltinFunction((_sf, x: number) => Math.exp(untagNumber(x))),
|
||||
log: new LuaBuiltinFunction((_sf, x: number, base?: number) => {
|
||||
@@ -103,6 +130,7 @@ export const mathApi = new LuaTable({
|
||||
}
|
||||
return Math.log(untagNumber(x)) / Math.log(untagNumber(base));
|
||||
}),
|
||||
// Power function (deprecated in Lua 5.4 but retained for compatibility)
|
||||
pow: new LuaBuiltinFunction((_sf, x: number, y: number) =>
|
||||
Math.pow(untagNumber(x), untagNumber(y))
|
||||
),
|
||||
@@ -121,7 +149,7 @@ export const mathApi = new LuaTable({
|
||||
return Math.atan2(untagNumber(y), untagNumber(x));
|
||||
}),
|
||||
|
||||
// Hyperbolic functions
|
||||
// Hyperbolic functions (deprecated in Lua 5.4 but retained for compatibility)
|
||||
cosh: new LuaBuiltinFunction((_sf, x: number) => Math.cosh(untagNumber(x))),
|
||||
sinh: new LuaBuiltinFunction((_sf, x: number) => Math.sinh(untagNumber(x))),
|
||||
tanh: new LuaBuiltinFunction((_sf, x: number) => Math.tanh(untagNumber(x))),
|
||||
|
||||
Reference in New Issue
Block a user