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
Roundrounds halves up, toward positive infinity:Round(2.5)is 3 butRound(-2.5)is -2. Round the absolute value and put the sign back if you need halves away from zero.Modkeeps the sign of the first argument, as C'sfmoddoes:Mod(-7.0, 3.0)is -1, not 2.Factorialreturns ani64and is exact only up to 20; from 21 on it returns the largesti64.AbsI,AbsI64,Gcd,GcdI64andLcmnever return a negative or wrapped value. When the true answer does not fit, they return the largest value of the type:AbsIof the smallestintis 2147483647, andLcm(65536, 65537)is 2147483647 too.GcdandGcdI64stay exact for the smallest value:GcdI64(-9223372036854775808, 4)is 4.Hypotsquares 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.
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)
endfmt.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.
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)
endFor 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.
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)
endMean 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.
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
endNaN, 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.
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| Job | Use |
|---|---|
| Distance between two points | Hypot |
| Direction of a vector | Atan2, then Degrees |
| Round to n decimals | Round(x * Pow10(n)) / Pow10(n) |
| Keep a value in a range | ClampI, ClampF |
| Reduce a fraction | Gcd |
| Detect a broken result | IsNaN, IsInf |
Constants and variables
PI
const PI: f64 = 3.14159import 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
endE
const E: f64 = 2.71828The example for this item is shown with the ones above: math-Sqrt.salam
TAU
const TAU: f64 = 6.28319The example for this item is shown with the ones above: math-Sqrt.salam
Functions
Sqrt
func Sqrt(x: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Sin
func Sin(x: f64): f64import 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)
endCos
func Cos(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Tan
func Tan(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Asin
func Asin(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Acos
func Acos(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Atan
func Atan(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Atan2
func Atan2(y: f64, x: f64): f64Atan 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): f64The example for this item is shown with the ones above: math-Sqrt.salam
Log10
func Log10(x: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Log2
func Log2(x: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Exp
func Exp(x: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Floor
func Floor(x: f64): f64import 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)
endCeil
func Ceil(x: f64): f64The example for this item is shown with the ones above: math-Floor.salam
Round
func Round(x: f64): f64Math.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): f64The example for this item is shown with the ones above: math-Floor.salam
Pow
func Pow(base: f64, power: f64): f64base raised to the power power.The example for this item is shown with the ones above: math-Sqrt.salam
Cbrt
func Cbrt(x: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Hypot
func Hypot(x: f64, y: f64): f64The example for this item is shown with the ones above: math-Sqrt.salam
Sign
func Sign(x: f64): f64The example for this item is shown with the ones above: math-Floor.salam
Min
func Min(a: f64, b: f64): f64import 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)
endMax
func Max(a: f64, b: f64): f64The example for this item is shown with the ones above: math-Min.salam
ClampF
func ClampF(x: f64, lo: f64, hi: f64): f64lo to hi.The example for this item is shown with the ones above: math-Min.salam
MinI
func MinI(a: int, b: int): intThe example for this item is shown with the ones above: math-Min.salam
MaxI
func MaxI(a: int, b: int): intThe example for this item is shown with the ones above: math-Min.salam
AbsI
func AbsI(x: int): intThe example for this item is shown with the ones above: math-Min.salam
ClampI
func ClampI(x: int, lo: int, hi: int): intlo 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): intimport 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)
endLcm
func Lcm(a: int, b: int): intThe example for this item is shown with the ones above: math-Gcd.salam
AbsI64
func AbsI64(x: i64): i64The example for this item is shown with the ones above: math-Min.salam
Mod
func Mod(x: f64, y: f64): f64x.The example for this item is shown with the ones above: math-Floor.salam
Trunc
func Trunc(x: f64): f64The example for this item is shown with the ones above: math-Floor.salam
IsNaN
func IsNaN(x: f64): bool== cannot detect it.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
endInf
func Inf(): f64The example for this item is shown with the ones above: math-IsNaN.salam
NaN
func NaN(): f64The example for this item is shown with the ones above: math-IsNaN.salam
IsInf
func IsInf(x: f64): boolThe example for this item is shown with the ones above: math-IsNaN.salam
Sinh
func Sinh(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Cosh
func Cosh(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Tanh
func Tanh(x: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Pow10
func Pow10(n: int): f64n.The example for this item is shown with the ones above: math-Sqrt.salam
Lerp
func Lerp(a: f64, b: f64, t: f64): f64a 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): f64The example for this item is shown with the ones above: math-Sin.salam
Degrees
func Degrees(rad: f64): f64The example for this item is shown with the ones above: math-Sin.salam
Factorial
func Factorial(n: int): i64n. 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): i64The example for this item is shown with the ones above: math-Gcd.salam
MinI64
func MinI64(a: i64, b: i64): i64The example for this item is shown with the ones above: math-Min.salam
MaxI64
func MaxI64(a: i64, b: i64): i64The example for this item is shown with the ones above: math-Min.salam