Standard library · Numbers and collections

math

The basic mathematics: powers and roots, logarithms, trigonometry, rounding, minimum and maximum, and the greatest common divisor.

import math

The math package holds what you would expect from a scientific calculator. Most of its functions work on f64; the ones whose names end in I or I64 are the whole-number versions.

The angles in the trigonometric functions are in radians, not degrees. Use Radians and Degrees to convert.

For averages, medians and percentiles of a list use stats; for money and other exact decimals, decimal; for whole numbers too large for i64, bigint; for random numbers, rand.

Behaviour worth knowing

  • Round rounds halves up, toward positive infinity: Round(2.5) is 3 but Round(-2.5) is -2. Round the absolute value and put the sign back if you need halves away from zero.
  • Mod keeps the sign of the first argument, as C's fmod does: Mod(-7.0, 3.0) is -1, not 2.
  • Factorial returns an i64 and is exact only up to 20; from 21 on it returns the largest i64.
  • AbsI, AbsI64, Gcd, GcdI64 and Lcm never return a negative or wrapped value. When the true answer does not fit, they return the largest value of the type: AbsI of the smallest int is 2147483647, and Lcm(65536, 65537) is 2147483647 too. Gcd and GcdI64 stay exact for the smallest value: GcdI64(-9223372036854775808, 4) is 4.
  • Hypot squares its arguments directly, so values above about 1e154 give infinity.

Distances, angles and circles

Most geometry in a program is a distance or a direction between two points. Hypot gives the straight line distance, and Atan2 gives the angle of a direction from all four quarters of the plane, which plain Atan cannot tell apart. Convert between degrees and radians at the edges of your program and keep radians inside it.

math-guide-geometry.salam
import math
import fmt

func distance(x1: f64, y1: f64, x2: f64, y2: f64): f64:
    ret math.Hypot(x2 - x1, y2 - y1)
end

func heading(x1: f64, y1: f64, x2: f64, y2: f64): f64:
    deg := math.Degrees(math.Atan2(y2 - y1, x2 - x1))
    if deg < 0.0: ret deg + 360.0 end
    ret deg
end

func main:
    println "distance:", distance(1.0, 2.0, 4.0, 6.0)
    println "heading east:", heading(0.0, 0.0, 5.0, 0.0)
    println "heading north:", heading(0.0, 0.0, 0.0, 5.0)
    println "heading south-west:", heading(0.0, 0.0, -3.0, -3.0)
    r := 2.5
    println "circle area:", fmt.FloatPrec(math.PI * math.Pow(r, 2.0), 2)
    println "circumference:", fmt.FloatPrec(math.TAU * r, 2)
    x := 10.0 * math.Cos(math.Radians(60.0))
    y := 10.0 * math.Sin(math.Radians(60.0))
    println "point at 60 degrees:", fmt.FloatPrec(x, 3), fmt.FloatPrec(y, 3)
end
Outputdistance: 5 heading east: 0 heading north: 90 heading south-west: 225 circle area: 19.63 circumference: 15.71 point at 60 degrees: 5.000 8.660

fmt.FloatPrec from fmt prints a number with a fixed count of decimals, which keeps results such as 8.660254037844386 readable.

Growth, loans and rounding

Pow handles compound growth and Log answers the reverse question of how long it takes. To round to a number of decimal places, multiply by Pow10, round, and divide again. The last two lines show why: f64 cannot store 0.1 exactly, so sums of prices pick up tiny errors.

math-guide-money.salam
import math
import fmt

func round_to(x: f64, places: int): f64:
    scale := math.Pow10(places)
    ret math.Round(x * scale) / scale
end

func monthly_payment(principal: f64, yearly_rate: f64, months: int): f64:
    r := yearly_rate / 12.0
    ret principal * r / (1.0 - math.Pow(1.0 + r, -(months as f64)))
end

func main:
    mut balance := 1000.0
    repeat 1 to 5 in year:
        balance *= 1.06
        println "year", year, fmt.FloatPrec(balance, 2)
    end
    println "after 5 years:", round_to(1000.0 * math.Pow(1.06, 5.0), 2)
    println "doubling time at 6%:", fmt.FloatPrec(math.Log(2.0) / math.Log(1.06), 1), "years"
    println "monthly payment:", fmt.FloatPrec(monthly_payment(20000.0, 0.18, 36), 2)
    println "0.1 + 0.2 =", 0.1 + 0.2
    println "rounded:", round_to(0.1 + 0.2, 2)
end
Outputyear 1 1060.00 year 2 1123.60 year 3 1191.02 year 4 1262.48 year 5 1338.23 after 5 years: 1338.23 doubling time at 6%: 11.9 years monthly payment: 723.05 0.1 + 0.2 = 0.30000000000000004 rounded: 0.3

For real money, where every cent must add up, use decimal instead of f64; the rounding trick above is fine for display and for estimates.

Whole numbers: Gcd and Lcm

The greatest common divisor reduces fractions and finds the largest tile or package size that divides evenly; the least common multiple finds the next time two repeating events line up. Both work on int; GcdI64 takes 64-bit values.

math-guide-fractions.salam
import math
import str

func show(n: int, d: int): str:
    g := math.Gcd(math.AbsI(n), math.AbsI(d))
    ret str.FromInt(n / g) + "/" + str.FromInt(d / g)
end

func add(an: int, ad: int, bn: int, bd: int): str:
    common := math.Lcm(ad, bd)
    ret show(an * (common / ad) + bn * (common / bd), common)
end

func main:
    println "12/18 =", show(12, 18)
    println "1/4 + 1/6 =", add(1, 4, 1, 6)
    println "3/10 + 7/15 =", add(3, 10, 7, 15)
    println "buses every 12 and 18 minutes meet every", math.Lcm(12, 18), "minutes"
    tiles := math.Gcd(240, 180)
    println "largest square tile for a 240 x 180 floor:", tiles
    println "tiles needed:", (240 / tiles) * (180 / tiles)
end
Output12/18 = 2/3 1/4 + 1/6 = 5/12 3/10 + 7/15 = 23/30 buses every 12 and 18 minutes meet every 36 minutes largest square tile for a 240 x 180 floor: 60 tiles needed: 12

Mean and spread by hand

Min, Max, Pow and Sqrt are enough for a small summary of a list. For anything bigger, such as the median, percentiles or a correlation, the stats package already has the functions.

math-guide-stats.salam
import math
import fmt

func main:
    scores := [72.0, 85.5, 90.0, 64.5, 88.0]
    mut sum := 0.0
    mut low := scores[0]
    mut high := scores[0]
    each s in scores:
        sum += s
        low = math.Min(low, s)
        high = math.Max(high, s)
    end
    mean := sum / 5.0
    mut squares := 0.0
    each s in scores:
        squares += math.Pow(s - mean, 2.0)
    end
    deviation := math.Sqrt(squares / 5.0)
    println "mean:", mean
    println "lowest:", low, "highest:", high
    println "standard deviation:", fmt.FloatPrec(deviation, 2)
    each s in scores:
        z := (s - mean) / deviation
        println s, "is", fmt.FloatPrec(math.Abs(z), 2), "deviations", z < 0.0 ? "below" : "above"
    end
end
Outputmean: 80 lowest: 64.5 highest: 90 standard deviation: 9.98 72 is 0.80 deviations below 85.5 is 0.55 deviations above 90 is 1.00 deviations above 64.5 is 1.55 deviations below 88 is 0.80 deviations above

NaN, infinity and comparing decimals

Dividing by zero does not stop a Salam program when the numbers are f64: it gives infinity, or NaN for zero divided by zero, and both spread silently through later sums. Check results that come from user data with IsNaN and IsInf. Never compare two computed decimals with ==; compare the size of their difference instead. ClampI and ClampF keep a value inside a range.

math-guide-safe.salam
import math

func safe_ratio(a: f64, b: f64): f64:
    r := a / b
    if math.IsNaN(r) or math.IsInf(r): ret 0.0 end
    ret r
end

func near(a: f64, b: f64): bool:
    ret math.Abs(a - b) < 0.000000001
end

func main:
    println "1 / 0 =", 1.0 / 0.0, "->", safe_ratio(1.0, 0.0)
    println "0 / 0 =", 0.0 / 0.0, "->", safe_ratio(0.0, 0.0)
    println "6 / 4 =", safe_ratio(6.0, 4.0)
    root := math.Sqrt(-4.0)
    println "sqrt(-4) is NaN:", math.IsNaN(root)
    println "cbrt(-8) =", math.Cbrt(-8.0)
    println "0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3
    println "near(0.1 + 0.2, 0.3):", near(0.1 + 0.2, 0.3)
    println "volume 130% clamped:", math.ClampI(130, 0, 100)
    println "opacity -0.2 clamped:", math.ClampF(-0.2, 0.0, 1.0)
end
Output1 / 0 = inf -> 0 0 / 0 = nan -> 0 6 / 4 = 1.5 sqrt(-4) is NaN: true cbrt(-8) = -2 0.1 + 0.2 == 0.3: false near(0.1 + 0.2, 0.3): true volume 130% clamped: 100 opacity -0.2 clamped: 0
JobUse
Distance between two pointsHypot
Direction of a vectorAtan2, then Degrees
Round to n decimalsRound(x * Pow10(n)) / Pow10(n)
Keep a value in a rangeClampI, ClampF
Reduce a fractionGcd
Detect a broken resultIsNaN, IsInf

Constants and variables

PI

const PI: f64 = 3.14159
Pi (π), the ratio of a circle's circumference to its diameter.
math-Sqrt.salam
import math

func main:
    println math.Sqrt(2.0), math.Cbrt(27.0), math.Pow(2.0, 10.0), math.Pow10(3)
    println math.Hypot(3.0, 4.0), math.Exp(1.0)
    println math.Log(math.E), math.Log10(1000.0), math.Log2(1024.0)
    println math.PI, math.TAU
end
Output1.4142135623730951 3 1024 1000 5 2.718281828459045 1 3 10 3.141592653589793 6.283185307179586

E

const E: f64 = 2.71828
Euler's number (e), the base of the natural logarithm.

The example for this item is shown with the ones above: math-Sqrt.salam

TAU

const TAU: f64 = 6.28319
Twice pi (τ); one full turn in radians.

The example for this item is shown with the ones above: math-Sqrt.salam

Functions

Sqrt

func Sqrt(x: f64): f64
The square root of a number. For a negative number it gives NaN.

The example for this item is shown with the ones above: math-Sqrt.salam

Sin

func Sin(x: f64): f64
The sine of an angle given in radians.
math-Sin.salam
import math
import fmt

func main:
    angle := math.Radians(30.0)
    println fmt.FloatPrec(math.Sin(angle), 4), fmt.FloatPrec(math.Cos(angle), 4), fmt.FloatPrec(math.Tan(angle), 4)
    println fmt.FloatPrec(math.Degrees(math.Asin(0.5)), 4), fmt.FloatPrec(math.Degrees(math.Acos(0.0)), 4), fmt.FloatPrec(math.Degrees(math.Atan(1.0)), 4)
    println fmt.FloatPrec(math.Degrees(math.Atan2(1.0, -1.0)), 4)
    println fmt.FloatPrec(math.Sinh(1.0), 4), fmt.FloatPrec(math.Cosh(1.0), 4), fmt.FloatPrec(math.Tanh(1.0), 4)
end
Output0.5000 0.8660 0.5774 30.0000 90.0000 45.0000 135.0000 1.1752 1.5431 0.7616

Cos

func Cos(x: f64): f64
The cosine of an angle given in radians.

The example for this item is shown with the ones above: math-Sin.salam

Tan

func Tan(x: f64): f64
The tangent of an angle given in radians.

The example for this item is shown with the ones above: math-Sin.salam

Asin

func Asin(x: f64): f64
The inverse sine, an angle in radians between minus π/2 and π/2.

The example for this item is shown with the ones above: math-Sin.salam

Acos

func Acos(x: f64): f64
The inverse cosine, an angle in radians between zero and π.

The example for this item is shown with the ones above: math-Sin.salam

Atan

func Atan(x: f64): f64
The inverse tangent, an angle in radians.

The example for this item is shown with the ones above: math-Sin.salam

Atan2

func Atan2(y: f64, x: f64): f64
The angle of the point (x, y) from the horizontal axis. Unlike Atan it works out the right quadrant. Note that y comes first.

The example for this item is shown with the ones above: math-Sin.salam

Log

func Log(x: f64): f64
The natural logarithm, to base e.

The example for this item is shown with the ones above: math-Sqrt.salam

Log10

func Log10(x: f64): f64
The logarithm to base ten.

The example for this item is shown with the ones above: math-Sqrt.salam

Log2

func Log2(x: f64): f64
The logarithm to base two.

The example for this item is shown with the ones above: math-Sqrt.salam

Exp

func Exp(x: f64): f64
e raised to the power of the number.

The example for this item is shown with the ones above: math-Sqrt.salam

Floor

func Floor(x: f64): f64
The largest whole number not greater than the value; for negatives it goes down (−2.5 gives −3).
math-Floor.salam
import math

func main:
    each x in [2.5, -2.5, 2.49]:
        println x, math.Floor(x), math.Ceil(x), math.Round(x), math.Trunc(x)
    end
    println math.Abs(-3.5), math.Sign(-3.5), math.Sign(0.0), math.Mod(7.5, 2.0)
end
Output2.5 2 3 3 2 -2.5 -3 -2 -2 -2 2.49 2 3 2 2 3.5 -1 0 1.5

Ceil

func Ceil(x: f64): f64
The smallest whole number not less than the value.

The example for this item is shown with the ones above: math-Floor.salam

Round

func Round(x: f64): f64
Rounds to the nearest whole number, taking a half upwards, as JavaScript's Math.round does: 2.5 gives 3 and −2.5 gives −2. For money and exact rounding see the decimal package.

The example for this item is shown with the ones above: math-Floor.salam

Abs

func Abs(x: f64): f64
The absolute value of a decimal number.

The example for this item is shown with the ones above: math-Floor.salam

Pow

func Pow(base: f64, power: f64): f64
base raised to the power power.

The example for this item is shown with the ones above: math-Sqrt.salam

Cbrt

func Cbrt(x: f64): f64
The cube root; it gives the correct negative answer for a negative number.

The example for this item is shown with the ones above: math-Sqrt.salam

Hypot

func Hypot(x: f64, y: f64): f64
The hypotenuse of a right triangle, that is √(x² + y²). It squares the arguments directly, so inputs above about 1e154 overflow to infinity.

The example for this item is shown with the ones above: math-Sqrt.salam

Sign

func Sign(x: f64): f64
The sign of a number: minus one, zero or one.

The example for this item is shown with the ones above: math-Floor.salam

Min

func Min(a: f64, b: f64): f64
The smaller of two decimal numbers.
math-Min.salam
import math

func main:
    println math.Min(2.5, 1.5), math.Max(2.5, 1.5), math.ClampF(1.7, 0.0, 1.0)
    println math.MinI(3, 8), math.MaxI(3, 8), math.AbsI(-9), math.ClampI(120, 0, 100)
    big := 9000000000 as i64
    println math.MinI64(big, 5 as i64), math.MaxI64(big, 5 as i64), math.AbsI64(-big)
    println math.Lerp(10.0, 20.0, 0.25)
end
Output1.5 2.5 1 3 8 9 100 5 9000000000 9000000000 12.5

Max

func Max(a: f64, b: f64): f64
The larger of two decimal numbers.

The example for this item is shown with the ones above: math-Min.salam

ClampF

func ClampF(x: f64, lo: f64, hi: f64): f64
Keeps a decimal number within the range lo to hi.

The example for this item is shown with the ones above: math-Min.salam

MinI

func MinI(a: int, b: int): int
The smaller of two whole numbers.

The example for this item is shown with the ones above: math-Min.salam

MaxI

func MaxI(a: int, b: int): int
The larger of two whole numbers.

The example for this item is shown with the ones above: math-Min.salam

AbsI

func AbsI(x: int): int
The absolute value of a whole number.

The example for this item is shown with the ones above: math-Min.salam

ClampI

func ClampI(x: int, lo: int, hi: int): int
Keeps a whole number within the range lo to hi, for holding a percentage between zero and a hundred, for instance.

The example for this item is shown with the ones above: math-Min.salam

Gcd

func Gcd(a: int, b: int): int
The greatest common divisor of two whole numbers.
math-Gcd.salam
import math

func main:
    println math.Gcd(12, 18), math.Lcm(4, 6)
    println math.GcdI64(1200000000 as i64, 1800000000 as i64)
    println math.Factorial(5), math.Factorial(20)
end
Output6 12 600000000 120 2432902008176640000

Lcm

func Lcm(a: int, b: int): int
The least common multiple of two whole numbers.

The example for this item is shown with the ones above: math-Gcd.salam

AbsI64

func AbsI64(x: i64): i64
The absolute value of a 64-bit whole number.

The example for this item is shown with the ones above: math-Min.salam

Mod

func Mod(x: f64, y: f64): f64
The remainder of dividing two decimal numbers; its sign follows the sign of x.

The example for this item is shown with the ones above: math-Floor.salam

Trunc

func Trunc(x: f64): f64
Drops the fractional part without rounding (−2.5 gives −2).

The example for this item is shown with the ones above: math-Floor.salam

IsNaN

func IsNaN(x: f64): bool
True when the number is "not a number". NaN is not equal to itself, so == cannot detect it.
math-IsNaN.salam
import math

func main:
    inf := math.Inf()
    nan := math.NaN()
    println inf, -inf, math.IsInf(inf), math.IsInf(1.0)
    println math.IsNaN(nan), math.IsNaN(1.0), nan == nan
end
Outputinf -inf true false true false false

Inf

func Inf(): f64
Returns positive infinity.

The example for this item is shown with the ones above: math-IsNaN.salam

NaN

func NaN(): f64
Returns a "not a number" value, the result of a meaningless operation such as zero divided by zero.

The example for this item is shown with the ones above: math-IsNaN.salam

IsInf

func IsInf(x: f64): bool
True when the number is positive or negative infinity.

The example for this item is shown with the ones above: math-IsNaN.salam

Sinh

func Sinh(x: f64): f64
The hyperbolic sine.

The example for this item is shown with the ones above: math-Sin.salam

Cosh

func Cosh(x: f64): f64
The hyperbolic cosine.

The example for this item is shown with the ones above: math-Sin.salam

Tanh

func Tanh(x: f64): f64
The hyperbolic tangent, also used in neural networks.

The example for this item is shown with the ones above: math-Sin.salam

Pow10

func Pow10(n: int): f64
Ten raised to the power n.

The example for this item is shown with the ones above: math-Sqrt.salam

Lerp

func Lerp(a: f64, b: f64, t: f64): f64
Linear interpolation: the point that lies between a and b at the fraction t. A t of zero is a and one is b.

The example for this item is shown with the ones above: math-Min.salam

Radians

func Radians(deg: f64): f64
Converts degrees to radians.

The example for this item is shown with the ones above: math-Sin.salam

Degrees

func Degrees(rad: f64): f64
Converts radians to degrees.

The example for this item is shown with the ones above: math-Sin.salam

Factorial

func Factorial(n: int): i64
The factorial of n. Exact up to 20; from 21 it returns the largest i64, 9223372036854775807. For larger ones see the bigint package.

The example for this item is shown with the ones above: math-Gcd.salam

GcdI64

func GcdI64(a: i64, b: i64): i64
The greatest common divisor of two 64-bit whole numbers.

The example for this item is shown with the ones above: math-Gcd.salam

MinI64

func MinI64(a: i64, b: i64): i64
The smaller of two 64-bit whole numbers.

The example for this item is shown with the ones above: math-Min.salam

MaxI64

func MaxI64(a: i64, b: i64): i64
The larger of two 64-bit whole numbers.

The example for this item is shown with the ones above: math-Min.salam