APN Mojo: arbitrary precision arithmetic and multidimensional arrays in pure Mojo

APN Mojo: arbitrary precision and array programming in pure Mojo

Hi everyone,

Meet APN Mojo! It’s a library for arbitrary-precision arithmetic and multidimensional arrays, written in pure Mojo and released under the Apache License 2.0. All numerical algorithms are implemented in Mojo, with no runtime dependency on GMP, MPFR, MPC, or Python.

Here is a small example: calculate exp(pi * sqrt(163)).

The result is more than 262 quadrillion, yet it falls short of an integer by less than one trillionth. APN Mojo can resolve that gap and carry guaranteed bounds through the calculation:

from apn_mojo import BallContext, ball


def main() raises:
    var context = BallContext(256)
    var angle = ball.pi_ball(256) * ball.sqrt(163, context=context)
    var value = ball.exp(angle, context=context)
    var gap = 262537412640768744 - value

    print("exp(pi * sqrt(163)):", value.midpoint().to_string(digits=50))
    print("gap to the integer:", gap.midpoint().to_string(digits=20))
    print("interval contains an integer:", ball.contains_integer(value))

Output:

exp(pi * sqrt(163)): 262537412640768743.99999999999925007259719818568888
gap to the integer: 7.4992740280181431112e-13
interval contains an integer: False

The first two lines display approximations. The last line checks the entire interval enclosing the result. That interval contains no integer, establishing that the tiny gap is real.

A Ball stores a midpoint and a radius. Each operation carries the bounds forward, accounting for input uncertainty and rounding error. Here, the bounds cover every step, from approximating pi to evaluating the exponential. ComplexBall extends this approach to complex calculations. The interval tutorial explains how to use these bounds with uncertain inputs too.

The library also provides:

  • Exact arithmetic. Integer and Rational grow as needed within storage limits. ExactComplex keeps both components rational. Integer division with / preserves the fraction: Integer(7) / 3 is exactly 7/3.
  • Precision and rounding you choose. Float and Complex support configurable binary precision, exponent bounds, five rounding modes, and optional traps. Each operation rounds once to its destination format; complex results round once per component.
  • Number theory and numerical functions. Modular arithmetic, primality tests, factorials, and binomial coefficients, alongside elementary functions and special functions including gamma, beta, zeta, Lambert W, and hypergeometric functions.
  • Multidimensional arrays. Batch[T] supports integers, rationals, floats, complex numbers, and real or complex balls, with slicing, reshaping, masks, and NumPy-style elementwise functions and broadcasting.
  • Reuse of scalar code. Apply a scalar function across arrays with vmap[f]. Use lift[f] to build reductions, running accumulations, outer products, and broadcasting calls from a binary function.
  • Totals that preserve small contributions. Floating-point and complex sum and dot keep intermediates exact and round only the final total. Supported large operations can use multiple CPU cores with the same numerical results as sequential execution.

For a batch example, construct a 2 × 3 array and use the built-in NumPy-style functions to divide its elements, sum along an axis, and broadcast a row across the array:

from apn_mojo import Batch, Integer, batch


def main() raises:
    var grid = Batch[Integer]([1, 2, 3, 4, 5, 6]).reshape([2, 3])
    var thirds = batch.divide(grid, 3)

    print("thirds:", thirds)
    print("row sums:", batch.sum(thirds, axis=1))
    print("broadcast addition:", batch.add(grid, Batch[Integer]([10, 20, 30])))

Output:

thirds: [[1/3, 2/3, 1], [4/3, 5/3, 2]]
row sums: [2, 5]
broadcast addition: [[11, 22, 33], [14, 25, 36]]

Division produces exact Rational values. The thirds stay exact through the row sums. In the last call, the three-element row broadcasts across both rows of the grid.

Custom functions work across batches too. Here, a scalar function computes the squared distance between two integers. The coordinates are near 10**100, yet differences of one remain exact:

from apn_mojo import Batch, Integer, lift, vmap


def squared_distance(value: Integer, center: Integer) raises -> Integer:
    var difference = value - center
    return difference * difference


def main() raises:
    var origin = Integer(10) ** 100
    var positions = Batch[Integer]([origin + 1, origin + 2, origin + 4])
    var centers = Batch[Integer]([origin, origin + 2])

    var distances = vmap[squared_distance](in_axes=(0, None))(
        positions, origin + 2
    )
    print("squared distances from origin + 2:", distances)
    print("all position-center pairs:", lift[squared_distance]().outer(positions, centers))

Output:

squared distances from origin + 2: [1, 0, 4]
all position-center pairs: [[1, 1], [4, 0], [16, 4]]

vmap applies the function to each position while sharing one center: 0 selects the mapped axis, and None keeps the second argument fixed. lift[f]().outer(...) applies that same function to every position–center pair, producing a 3 × 2 array. The scalar function needs no batch-specific code.

The library also supports conversion to native Mojo types and versioned JSON formats that preserve stored values and formats exactly. The documentation includes runnable examples, API references, implementation details, and benchmark results.

APN Mojo supports Mojo 1.1.0 on Linux x86-64 and macOS arm64. With Pixi installed, you can try any of these examples from a source checkout:

git clone https://github.com/Spellbound-Mojo/apn_mojo.git
cd apn_mojo
pixi install --locked

Save any one of the programs above as showcase.mojo in the apn_mojo checkout. From that directory, run:

pixi run --locked mojo run -I src showcase.mojo

A package for the Modular community channel on prefix.dev is also in progress. Follow the packaging pull request for updates.

I’d love to hear what you build with it! Numerical edge cases, API feedback, and contributions are welcome.

1 Like

Great! you might be interested in numax.

1 Like

Thanks for sharing, @anatolvitold! :partying_face:

1 Like

I am interested! :slight_smile: It seems that numax serves a different purpose, since apn_mojo is designed as a backend for arbitrary-precision calculations in a CAS, while numax targets fixed-precision numerics on accelerators.
Still, it’s very interesting!

1 Like