Stories: Math

See also: spec/math.md — the rules these chapters explain.

Math as intrinsics, not a C foreign-function interface

Until this point a Zane program could add, multiply, divide, negate, and compare numbers, and nothing else. Those are the machine operations of @operators$, which core’s operators are written over, and they were enough for the programs we had been writing. They were not enough for the first program that wanted the distance between two points, which needs a square root, or for the first hash function, which needs shifts and exclusive or. Every language has these, so the question was not whether Zane should, but where they would come from.

There were two roads, and the second road was tempting. The first was to make them intrinsics, the way the arithmetic already was: operations the compiler supplies, stated over the storage primitives, which core wraps for its own types. The second was to give Zane a mechanism for calling C, and then write the math library as calls into the C library every platform already ships. That second road offered more than math. One interface to C would bring every function C has, and the math library would come for free with it.

What stopped us was everything else such an interface would have to settle first. A C function can write a file, open a socket, or read the clock, with no capability passed to it, and Zane’s effect model rests on there being no ambient way to reach external state (effects.md §6.1). C pointers have no place among Zane’s owners and references, and C code gets none of the guarantees a spawned call relies on. A program that links a C library also stops being a program one machine can build for every target. None of these questions is about math, and we did not want the square root to wait on all of them. And for math in particular the interface would have made the result worse, not just later. A call into C is opaque to the compiler, so sqrt(16.0) could no longer be computed at compile time or become the single instruction every modern CPU has for it, and its result would be whatever that platform’s C library decided, including the error code C’s math functions set on the side.

So math became intrinsics, in a namespace of their own (math.md §2). They have the shape of the machine operations exactly: each takes operands of one scalar primitive and has one overload per primitive it takes, so converting stays a separate, written step. Zig made the same call, with @sqrt and @popCount as compiler builtins behind the same @ that marks Zane’s intrinsics. A C interface may still come one day, for libraries that really are written in C, and it will have to answer the questions above on its own terms; math no longer depends on it.

The bit operations raised one question of their own, which was whether they should be operators. The operator set is fixed (operators.md §1), and every token in it already has a meaning on Int: ~ negates, * multiplies, + adds. Giving Int a bitwise meaning for any of them would have given one token two meanings on one type, and adding tokens for shifts would have grown a vocabulary we had kept small on purpose. So they are named functions, prefixed bit where the plain name would collide with the Boolean connectives and, or and not of @operators$ (math.md §2.3). A hash function reads more verbosely than its C original for it.

The cost of the intrinsic road is that the set is closed. A function the compiler does not supply cannot be added by a package as a primitive; a package writes it in Zane over the functions that exist, which is how most of a math library is written anyway.

Exact and approximate functions in one namespace, @math$

The first name we had for the namespace was @machine$, because we thought of its members as single machine operations, like the arithmetic beneath the operators. That held for the first function we looked at. The square root is a machine operation: x86 has an instruction for it and so does ARM, and IEEE 754 requires its result to be correctly rounded, exactly as it requires of addition. The cube root broke the name. No mainstream CPU has an instruction for it, and IEEE 754 only recommends a correctly rounded result rather than requiring one. The sine, the logarithm and the power function are in the same position. They are computed by a routine, and every routine produces a value near the true result.

That split the set along a line that matters more than whether an instruction exists: whether the result is fully specified. So the spec sorts every function into exact or approximate (math.md §2.2), and we named the namespace for the purpose they all share, @math$, under the rule that a namespace is named for its members’ nature or purpose (syntax.md §2.7). We had briefly worried that @math$ would be confused with a package called math. It will not be: the @ already marks an intrinsic, and with the math functions living in core there is no math package to confuse it with.

An exact function had to be exact at its edges too, and the edges were settled the way the integer operations had settled theirs: every exact function has a result for every operand. A shift by more than the width of the type is undefined in C and poison in LLVM, so we had to pick a value. We took the count modulo the width, as x86 and ARM do in hardware, so the rule costs nothing; a count of 64 on a 64-bit integer moves nothing. leadingZeros of zero gives the width, and abs of the most negative integer gives it back, wrapping as negate already did. The float functions are IEEE 754’s operations of the same names (math.md §2.5). The one choice there was min and max given a NaN, where IEEE 754 offers two behaviours: one returns the other operand, the other returns the NaN. We took the second, because a NaN usually signals an earlier failed computation, and a min that quietly drops it hides that.

The approximate functions were the harder decision. One road was to write them ourselves, in Zane, as correctly rounded routines over the exact functions, the way the CORE-MATH project has done for C. Every platform would then give the same answer to the last bit, which suits a spec that pins everything else. It is also a large project in numerical analysis, and the math library would have waited for it. The other road was the C math library every platform already ships, glibc on Linux, libSystem on macOS, the C runtime on Windows. That library is fast and available today, and its one fault started this chapter: the platforms give different results. They are usually within a unit in the last place of each other, and they are not identical.

We took the platform’s library and stated that choice plainly in the spec. An approximate function’s result is close to the true value, may differ between platforms, and within one program gives the same result for the same operands; for NaNs, infinities and operands outside its domain it follows IEEE 754 (math.md §2.6). That last guarantee mattered because of compile-time evaluation, which guarantees that computing a value ahead of time changes nothing the program computes (effects.md §5.3). A compiler that evaluated sin with the build machine’s library would break that promise whenever the target’s library disagreed, so an approximate function evaluated at compile time has to give the result it gives where the program runs. In practice the compiler therefore leaves them to run time.

The cost is reproducibility. A program that prints a sine to seventeen digits may print a different last digit on another operating system, and a test that compares such output exactly will fail there. Nothing in the language hides that. If Zane later carries correctly rounded versions of its own, the results only become more precise, and the spec’s word “approximate” still describes them.

The math functions move out of core into a math package

The first home we gave the math functions was core, beside the Int and Float they take. It was the obvious place: one import core$ would bring a program its numbers and everything it could compute on them, and core’s own declarations could read the private _value inside each one directly. The functions were written there, tested there, and nearly merged there.

A question about the purpose of core moved them. core declares the fundamental types (types.md §2.6): the numbers, strings and containers nearly every program is written in terms of, with the operators and conversions that make them usable. A square root is not part of the definition of a Float. Once the functions story had made every math function a free function rather than a method, nothing tied it to the package that declares its operand’s type, and putting it in core only made core the place where everything numeric collects. Most languages keep the two apart. C has <math.h> beside its arithmetic, Go and Python a math package, Zig std.math. Rust is the exception, with its math as methods on the primitives, and that was the road we had already turned down.

So the functions became a package of their own, math, in the same project as core (math.md §3.1). It had to be a top-level library package rather than a subpackage at lib/core/math/, because a subpackage is never visible to another project, and a math library no program can import is no use (packages.md §2.3). Being a separate package, math cannot read _value, which is private to core. It passes its operands to the intrinsics through core’s implicit conversions to the storage primitives instead, which any package may use. That turned out to be a point in the move’s favour: math is written on exactly the terms any other package would be, so it shows that what core makes public is enough to build a numeric library on.

The cost is a second import. A file that computes a square root now writes import math$ beside import core$, since no package arrives without being named (packages.md §3.1), and a reader meets sqrt without knowing which import supplied it unless they look. The move also undid a reassurance from the chapter before this one, that @math$ could not be confused with a package called math because there was none. Now there is one, and sqrt exists twice, as @math$sqrt on @primitives$F64 and as math’s sqrt on Float. We kept the shared name on purpose. The @ still marks which is the compiler’s, and the two are one function at two levels, the package’s a thin wrapper over the intrinsic it is named after.