Reference · Math

math.ldexp

signature
math.ldexp(num, int) -> float

What it does

x * 2^e, as a float, as Python's math.ldexp: the inverse of math.frexp. math.ldexp(0.5, 4) is 8.0. Scaling by a power of two is exact, so no precision is lost as long as the result is a normal float.

Examples

print(math.ldexp(0.5, 4), math.ldexp(3, 2), math.ldexp(1, -1), math.ldexp(1.5, 0))let [m, e] = math.frexp(10)print(math.ldexp(m, e))
output
8.0 12.0 0.5 1.510.0

Edge cases

print(math.ldexp(1, -1074) > 0, math.ldexp(1, -1075))print(math.ldexp(0, 100000), math.ldexp(float("inf"), 1), math.ldexp(1, 2.0))
output
true 0.00.0 inf 4.0

Errors

A result too large for a float is a runtime error, math range error, not infinity and not an error value: math.ldexp(1, 1024) fails while math.ldexp(1, 1023) is the largest power of two. An exponent that is not a whole number, or a first argument that is not a number, is a runtime error as well.

this one fails
print(math.ldexp(1, 1024))
output
line 1: `math.ldexp`: math range error (1)
this one fails
print(math.ldexp(1, 0.5))
output
line 1: `math.ldexp` expects an int as argument 2, got float

Chaining

In a pipeline the number comes first, so x | math.ldexp(e) scales x by 2^e:

print(3 | math.ldexp(3))print([1, 2, 3] | map((x) => math.ldexp(x, 10)))
output
24.0[1024.0, 2048.0, 3072.0]

See also

math.frexp, math.pow, math.exp2

Thread
6Useful? Like it, or add to its thread below.

Thread 0 posts

On math.ldexp(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo