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 away from zero, like C and Rust: Round(2.5) is 3 and Round(-2.5) is -3. Use Floor(x + 0.5) if you want halves to go up.
•
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.
•
Functions ending in F32 take and return f32. SqrtF32, ModF32, AbsF32, FloorF32, CeilF32, RoundF32, TruncF32, MinF32 and MaxF32 are exact or correctly rounded, so every backend gives the same answer. The others work out the f64 result and round it to f32, which is almost always the nearest f32, but can differ by one unit in the last place between platforms.
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.
distance: 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.
year 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.
12/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
funcmain:
scores := [72.0, 85.5, 90.0, 64.5, 88.0]
mut sum := 0.0mut 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.0mut squares := 0.0each 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"endend
Output
mean: 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
funcsafe_ratio(a: f64, b: f64): f64:
r := a / b
if math.IsNaN(r) or math.IsInf(r): ret0.0endret r
endfuncnear(a: f64, b: f64): bool:
ret math.Abs(a - b) < 0.000000001endfuncmain:
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.3println"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
JobUseDistance between two pointsHypotDirection of a vectorAtan2, then DegreesRound to n decimalsRound(x * Pow10(n)) / Pow10(n)Keep a value in a rangeClampI, ClampFReduce a fractionGcdDetect a broken resultIsNaN, IsInf
The largest whole number not greater than the value; for negatives it goes down (−2.5 gives −3).
math-Floor.salam
import math
funcmain:
each x in [2.5, -2.5, 2.49]:
println x, math.Floor(x), math.Ceil(x), math.Round(x), math.Trunc(x)
endprintln math.Abs(-3.5), math.Sign(-3.5), math.Sign(0.0), math.Mod(7.5, 2.0)
end
Rounds to the nearest whole number, taking a half away from zero, as C's round does: 2.5 gives 3 and −2.5 gives −3. For money and exact rounding see the decimal package.
The example for this item is shown with the ones above: math-Floor.salam
True when the number is "not a number". NaN is not equal to itself, so == cannot detect it.
math-IsNaN.salam
import math
funcmain:
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