IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

FastDiv

struct FastDiv[dtype: DType]

Implements fast division for a given type.

This struct provides optimized division by a constant divisor, replacing the division operation with a series of shifts and multiplications. This approach significantly improves performance, especially in scenarios where division is a frequent operation.

Parameters

  • dtype (DType): The data type for the division operation.

Implemented traits

AnyType, Copyable, ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable, TrivialRegisterPassable, Writable

comptime members

uint_type

comptime uint_type = _uint_type_of_width[bit_width_of[dtype]()]()

The unsigned integer type used for the fast division algorithm.

Methods

__init__

__init__(divisor: Int = 1) -> Self

Initializes FastDiv with the divisor.

Constraints:

ConstraintError: If the bitwidth of the type is > 64.

Args:

  • divisor (Int): The divisor to use for fast division. Defaults to 1.

__rtruediv__

__rtruediv__(self, other: Scalar[FastDiv[dtype].uint_type]) -> Scalar[FastDiv[dtype].uint_type]

Divides the other scalar by the divisor (true division).

Uses the fast division algorithm, with optimized path for power-of-2 divisors.

Args:

Returns:

Scalar[FastDiv[dtype].uint_type]: The result of the division.

__rmod__

__rmod__(self, other: Scalar[FastDiv[dtype].uint_type]) -> Scalar[FastDiv[dtype].uint_type]

Computes the remainder of division.

Args:

Returns:

Scalar[FastDiv[dtype].uint_type]: The remainder.

__rdiv__

__rdiv__(self, other: Scalar[FastDiv[dtype].uint_type]) -> Scalar[FastDiv[dtype].uint_type]

Divides the other scalar by the divisor.

Args:

Returns:

Scalar[FastDiv[dtype].uint_type]: The result of the division.

__divmod__

__divmod__(self, other: Scalar[FastDiv[dtype].uint_type]) -> Tuple[Scalar[FastDiv[dtype].uint_type], Scalar[FastDiv[dtype].uint_type]]

Computes both quotient and remainder.

Args:

Returns:

Tuple[Scalar[FastDiv[dtype].uint_type], Scalar[FastDiv[dtype].uint_type]]: A tuple containing the quotient and remainder.

write_to

write_to[W: Writer](self, mut writer: W)

Writes the FastDiv parameters to a writer.

Parameters:

  • W (Writer): The type of the writer.

Args:

  • writer (W): The writer to which the parameters are written.