# Math Namespace

`Math` provides builtin numeric operations and constants without an import.
Choose the operation and numeric width first; container support and backend
lowering are separate considerations.

## Quick Examples

This complete scalar example checks its results instead of relying on the
printed spelling of floating-point values:

```vex [math-scalar.vx]
fn main(): i32 {
    let root: f64 = Math.sqrt(144.0);
    let root32: f32 = Math.sqrtf(144.0 as f32);
    let angle: f64 = Math.PI / 4.0;
    let sine: f64 = Math.sin(angle);
    if root != 12.0 || root32 != (12.0 as f32) { return 1; }
    if Math.abs(sine - 0.7071067811865476) > 0.000000000001 { return 2; }
    if !Math.isFinite(sine) { return 3; }
    $println("scalar math: PASS");
    return 0;
}
```

Expected output is `scalar math: PASS` and exit status 0. The tolerance is
specific to this example; select an error budget appropriate to an application's
scale and algorithm. A `NaN` never compares equal to itself: use `Math.isNaN`
when classifying a value.

## Scalar vs Vectorized Usage

The scalar transcendental functions below use `f64`; the explicitly listed
`f` variants use `f32`. `min`, `max`, `clamp`, `abs`, and integer bit operations
have type-preserving forms. Do not infer a function's result width from the
width of an untyped numeric literal.

The compiler also has lifting rules for selected arrays and Tensor operations.
Those rules do not make every scalar API available for every container.
A `Span` is a borrowed view with a lifetime and length; it is not interchangeable
with an owning Tensor. Consult the [SIMD/SIMT contract](simd/simd-simt-contract.md)
for supported shapes and execution paths.

Vectorizable source can lower to scalar work, LLVM vector operations, library
calls or SIR operations. There is no blanket single-instruction `sin`, `exp`
or `log` guarantee, and a `graph fn` does not by itself prove GPU execution.

## Trigonometric

Angles use radians. Unary entries have scalar signature `(f64) -> f64`;
`atan2` takes `(y: f64, x: f64)`.

| Function | Meaning |
| --- | --- |
| `Math.sin(x)`, `Math.cos(x)`, `Math.tan(x)` | Sine, cosine and tangent |
| `Math.asin(x)`, `Math.acos(x)` | Inverse sine/cosine; real-valued domain is `[-1, 1]` |
| `Math.atan(x)` | Inverse tangent |
| `Math.atan2(y, x)` | Angle using both coordinates to determine the quadrant |

## Hyperbolic

`Math.sinh`, `cosh`, `tanh`, `asinh`, `acosh`, and `atanh` each take and return
`f64`. Real-valued inverse domains differ: `acosh` requires `x >= 1` and
`atanh` requires `-1 < x < 1` for a finite result.

## Exponential & Logarithmic

| Function | Meaning |
| --- | --- |
| `Math.exp(x)`, `Math.exp2(x)` | `e^x`, `2^x` |
| `Math.expm1(x)` | `exp(x) - 1`, avoiding cancellation near zero |
| `Math.log(x)`, `Math.ln(x)` | Natural logarithm; `ln` is an alias |
| `Math.log2(x)`, `Math.log10(x)` | Base-2 and base-10 logarithms |
| `Math.log1p(x)` | `log(1 + x)`, retaining accuracy near zero |

These scalar operations take and return `f64`. A finite real logarithm requires
a positive argument (`x > -1` for `log1p`). These are numeric operations, not
`Result`-returning input validators; validate application input before calling.

## Power & Root

| Function | Scalar arguments | Meaning |
| --- | --- | --- |
| `Math.pow(base, exponent)` | Two `f64` values | Floating-point power |
| `Math.sqrt(x)` | `f64` | Square root |
| `Math.cbrt(x)` | `f64` | Cube root, including negative inputs |
| `Math.rsqrt(x)` | `f64` | Reciprocal square root |
| `Math.hypot(x, y)` | Two `f64` values | Euclidean magnitude |
| `Math.copysign(x, y)` | Two `f64` values | Magnitude of `x` with the sign of `y` |
| `Math.fmod(x, y)` | Two `f64` values | Floating-point remainder |

Use `cbrt` when the mathematical operation is a real cube root; replacing it
with a fractional `pow` changes behavior for negative inputs.

## Rounding

| Function | Direction |
| --- | --- |
| `Math.floor(x)` | Toward negative infinity |
| `Math.ceil(x)` | Toward positive infinity |
| `Math.round(x)` | Nearest integral value; halfway cases away from zero |
| `Math.trunc(x)` | Toward zero |
| `Math.rint(x)` | Integral value according to the rounding mode used by its lowering |

These return floating-point values. They do not perform an integer conversion.
Validate finiteness and the destination range before converting to an integer.
Do not use `rint` as an unconditional promise of banker's rounding across all
execution environments.

## Comparison & Clamping

`Math.min(a, b)`, `max(a, b)`, `clamp(x, lo, hi)`, `abs(x)` and `sign(x)`
preserve the operand type on their scalar paths. Use matching argument types
and an ordered interval (`lo <= hi`) for clamping. Integer absolute value
cannot represent the positive magnitude of the minimum signed integer in that
same type; do not use it as an overflow check.

`Math.fmin` and `fmax` are floating-point comparisons. Their native LLVM
lowering uses `minnum`/`maxnum`: a single NaN operand selects the other numeric
operand. Neither call is a replacement for checking that both inputs satisfy
an application's validity policy.

`Math.isNaN`, `Math.isInf`, and `Math.isFinite` accept scalar `f32` or `f64`
and return `bool`. The spelling is significant.

## Activation Functions (ML)

`Math.relu(x)` computes `max(0, x)` and `Math.sigmoid(x)` expresses the logistic
function; `Math.erf(x)` is the error function. The scalar family uses `f64`.
For model-level normalization, softmax, attention and their shape contracts,
see [`ml`](../std/ml.md). Mathematical names alone do not establish numerical
stability for every magnitude, empty input or non-finite value.

## Bit Operations

| Function | Scalar contract |
| --- | --- |
| `Math.popcount(x)` | Count set bits; preserves integer width/type |
| `Math.clz(x)` / `Math.ctz(x)` | Leading/trailing zero count in the operand's width |
| `Math.bswap(x)` | Reverse bytes without changing integer width |
| `Math.nextPowerOf2(x)` / `Math.nextPow2(x)` | Width-preserving next power of two |

For example, `Math.clz(4 as u32)` is `29`, while `Math.clz(4 as u64)` is `61`.
Masked extraction/deposition live in the separate [Bit namespace](bit.md).

### Scalar next power of two at compile time

Both spellings preserve the operand's integer type and bit width, including
`usize`/`isize` on the compilation target and 128-bit integers. Known scalar
operands can be evaluated in `#const` or a const function through the ordinary
`Math` API; no separate intrinsic spelling is needed.

```vex
let buckets: usize = #const { Math.nextPow2(1000001 as usize) }; // 1048576
let high: u128 = #const { Math.nextPowerOf2(((1 as u128) << 100) + 1 as u128) };
```

This is a **wrapping bit-pattern operation**: zero returns zero, and a result
outside the operand width wraps to zero. Signed inputs retain signedness and
use their underlying bits; for example, `Math.nextPow2(127 as i8)` yields
`-128`. For allocation sizes use unsigned inputs and checked `Layout`/collection
APIs, which reject invalid extents. This scalar CTFE support does not imply
array, Span, Tensor, or GPU next-power support.

## Float Bit Representation

`Math.toBits` and `Math.fromBits` reinterpret a scalar's representation. They
are not numeric casts and preserve signed zero and every NaN payload bit.

| Function | Signature | Result |
|---|---|---|
| `Math.toBits(x)` | `f32 -> u32`, `f64 -> u64` | Same-width IEEE-754 bits |
| `Math.fromBits(x)` | `u32 -> f32`, `u64 -> f64` | Same-width IEEE-754 value |

```vex
let negativeZero = Math.fromBits(0x8000000000000000 as u64);
let payload = Math.toBits(negativeZero); // exact same u64
```

Both operations lower to one LLVM SSA `bitcast`. They perform no memory copy,
allocation, libc call or FFI transition. Other integer widths and signed
integer arguments are rejected rather than implicitly narrowed or re-signed.

## Angle Conversion

`Math.degrees(x)` converts radians to degrees; `Math.radians(x)` converts
degrees to radians. The unsuffixed scalar functions take/return `f64`;
`degreesf` and `radiansf` are the `f32` forms.

```vex
let degrees: f64 = Math.degrees(Math.PI); // approximately 180
let radians: f32 = Math.radiansf(90.0 as f32);
```

## Random Numbers

`Math.random()` takes no arguments and returns an `f64` in `[0, 1)`. It is not
an array/Span/Tensor operation and is not a cryptographic randomness API.
For reproducible simulations and unbiased integer ranges, prefer an explicit
[`rand.Rng`](../std/rand.md) stream. Use [`Crypto.secureRand`](crypto.md#secure-random)
for the OS-backed randomness primitive; it does not by itself implement a
complete key-management or nonce-allocation policy.

## Constants

The builtin constants are `f64` values:

| Constant | Meaning |
| --- | --- |
| `Math.PI`, `Math.TAU` | π and 2π |
| `Math.E` | Euler's number |
| `Math.SQRT2` | Square root of 2 |
| `Math.LN2`, `Math.LN10` | Natural logarithms of 2 and 10 |
| `Math.LOG2E`, `Math.LOG10E` | Base-2/base-10 logarithms of e |
| `Math.FRAC_PI_2`, `Math.FRAC_PI_4` | π/2 and π/4 |
| `Math.FRAC_1_SQRT2` | Reciprocal square root of 2 |
| `Math.PHI` | Golden ratio |
| `Math.EPSILON` | The `f64` machine epsilon; not a universal comparison tolerance |
| `Math.INF`, `Math.NAN` | Positive infinity and NaN |

## f32 Variants

These explicit spellings select the `f32` scalar family:

| Operation | `f32` spelling |
| --- | --- |
| Sine / cosine / hyperbolic tangent | `sinf`, `cosf`, `tanhf` |
| Exponentials | `expf`, `exp2f` |
| Logarithms | `logf`, `log2f`, `log10f` |
| Square root / absolute value | `sqrtf`, `fabsf` |
| Rounding | `floorf`, `ceilf`, `roundf`, `truncf`, `rintf` |
| Power / copy sign | `powf`, `copysignf` |
| Floating minimum/maximum | `fminf`, `fmaxf` |
| Angle conversions | `degreesf`, `radiansf` |

Prefix these names with `Math.`. There is no general rule that adding `f` to
an arbitrary function name creates another overload.

## LLVM Backend

The native backend uses operation-specific recipes. Some become LLVM intrinsics
(such as `llvm.sqrt`); others call mathematical library functions (such as
`atan2` or `expm1`). LLVM then selects legal instructions for the target. An
LLVM intrinsic is not a hardware latency measurement. Inspect and benchmark
the complete compiled workload if vectorization or throughput is a requirement.

## Next Steps

- [Bit operations](../std/bit.md)
- [SIMD and tensors](simd/index.md)
- [Random streams](../std/rand.md)
