Skip to content

math

Math constants, integer helpers (gcd, lcm) and a float comparison with tolerance.

Most math in Brass is not in this module: it is methods on f64 (and f32), with no import needed. They are abs, sqrt, cbrt, pow(y), exp, ln, log2, log10, log(base), sin, cos, tan, asin, acos, atan, atan2(x), sinh, cosh, tanh, hypot(y), floor, ceil, round, trunc, min(y), max(y), is_nan, is_finite, is_infinite, to_i64 and to_str. Integers have abs, min, max and conversions such as to_f64.

Area of a circle, and degrees to radians:

import math
let r = 2.0
print(f"{math.PI * r * r:.2}")
let degrees = 90.0
print((degrees * math.PI / 180.0).sin())
12.57
1.0

Compare floats. Rounding makes == unreliable for computed values; close allows a relative tolerance:

import math
print(0.1 + 0.2 == 0.3)
print(math.close(0.1 + 0.2, 0.3, 0.000000001))
false
true

Reduce a fraction, and find when two cycles line up:

import math
let (num, den) = (12, 18)
let g = math.gcd(num, den)
print(f"{num / g}/{den / g}")
print(math.lcm(4, 6))
2/3
12

Two things to know about numbers in general:

  • A method call binds tighter than unary minus, so -2.0.sqrt() is -(2.0.sqrt()). Write (-x).abs() when you mean the negative number.
  • Integer division truncates toward zero (7 / -2 is -3), and overflow or division by zero stops the program instead of wrapping.
import math
pub fn gcd(a: i64, b: i64) -> i64

The greatest common divisor, never negative; gcd(0, 0) is 0.

pub fn lcm(a: i64, b: i64) -> i64

The least common multiple, never negative; 0 when either is 0.

Computed as a / gcd(a, b) * b, so the result can still overflow i64 for large inputs; overflow stops the program.

pub fn close(a: f64, b: f64, tolerance: f64) -> bool

Whether two floats are within tolerance of each other, relative to their size.

The tolerance is relative to the larger of the two magnitudes, but never smaller than an absolute tolerance (the scale is at least 1.0). So close(1000000.0, 1000001.0, 0.000001) is true, and near zero it behaves like an absolute check. NaN is never close to anything.

pub const PI: f64

The ratio of a circle’s circumference to its diameter.

pub const TAU: f64

A full turn in radians, 2 * PI.

pub const E: f64

The base of the natural logarithm.