Skip to content

compute.ndarray.cast

Summary

compute.ndarray.cast converts numeric representation while preserving shape and residency. Use it to prepare a GPU input for an operation that requires a different dtype, such as converting f64 storage to f32 arithmetic. The result stores elements in packed C order.

Syntax

cast<T extends CPUndarray | GPUndarray>(a: T, dtype: DType, options?: NdarrayCastOptions): T
const result = nd.cast(a, "i16", { rounding: "nearest-even" });

Parameters

Name Type Required Description
a CPUndarray | GPUndarray Yes Live input, including strided views.
dtype DType Yes Destination element type.
options NdarrayCastOptions No Integer conversion and GPU output options.

Returns

T - Converted array in the source residency. Destroy a newly allocated result when finished. A supplied GPU out is returned directly.

Type Details

type NdarrayOverflowMode = "wrap" | "saturate";
type NdarrayRoundingMode = "trunc" | "nearest-even";
type NdarrayCastOptions = NdarrayOperationOptions & {
    overflow?: NdarrayOverflowMode;
    rounding?: NdarrayRoundingMode;
};

For an integer destination, rounding defaults to truncation toward zero. "nearest-even" rounds ties to the nearest even integer. Overflow defaults to saturation for floating inputs and wraparound for integer inputs. Saturation clamps to the representable range. NaN converts to zero in an integer destination.

GPU output allocation, aliasing, and submission follow compute.ndarray.contiguous.

Example

const wgpu = await WasmGPU.create(document.querySelector("canvas"));
const nd = wgpu.compute.ndarray;
const a = nd.fromArray("f32", [3], [2.5, -1, 300]);
const b = nd.cast(a, "u8", { rounding: "nearest-even" });
console.log(b.data()); // [2, 0, 255]
b.destroy();
a.destroy();

Notes

Real-to-complex conversion gives a zero imaginary component. To convert a complex input to a real type, first select a component with real() or imag(). GPU casts between integer and f64 or c128 throw. Use a CPU array or an intermediate f32 or c64 conversion as appropriate.

See Also