math
The math module has the floating-point functions: square root, rounding, logarithms and exponentials, powers, trigonometry, and pi, and popcount for bits. Every float function takes and returns float; this page shows how to get an int back out, and what happens at the edges (negative square roots, logarithms of zero, halfway rounding).
import math
fn main():
print(math.sqrt(16.0), math.pow(2.0, 10.0), math.round(2.5), math.floor(-2.5), math.pi())4.0 1024.0 3.0 -3.0 3.141592653589793All of them take float arguments. Tern never converts an int for you, so write math.sqrt(float(n)). To turn the result back into an int, use int(...), which cuts off the fraction: int(math.round(x)), int(math.floor(x)).
The functions map directly to the C library (sqrt, floor, round, ...), so they are as fast as in C and follow IEEE 754: a result that doesn't exist is NaN ("not a number"), and one that is too big is infinity. Neither is an error, and neither stops the program.
sqrt
fn sqrt(x: float) floatThe square root of x. The builtin sqrt(x) is the same function without the import. sqrt of a negative number is NaN.
pow
fn pow(x: float, y: float) floatx raised to the power y. Tern has no ** operator; this is it. pow(0.0, 0.0) is 1.0, and a negative x with a fractional y is NaN. For integer powers of integers, a loop is exact where pow may not be for results above 2<sup>53</sup>.
import math
fn main():
print(math.sqrt(2.0), sqrt(9.0), math.pow(2.0, 0.5), math.pow(10.0, -2.0), math.pow(0.0, 0.0))
n = 49
print(int(math.sqrt(float(n))))1.4142135623730951 3.0 1.4142135623730951 0.01 1.0
7floor
fn floor(x: float) floatThe largest whole number not greater than x (rounds toward minus infinity).
ceil
fn ceil(x: float) floatThe smallest whole number not less than x (rounds toward plus infinity).
round
fn round(x: float) floatx rounded to the nearest whole number. Halfway cases round away from zero: 2.5 becomes 3.0 and -2.5 becomes -3.0. (This is C's round, not the "banker's rounding" of Python's round.)
The three rounding functions return a float. int(x) on its own truncates toward zero, which differs from floor for negative numbers:
import math
fn main():
for x in [2.5, -2.5, 2.4, -0.5]:
print(x, math.floor(x), math.ceil(x), math.round(x), int(x))2.5 2.0 3.0 3.0 2
-2.5 -3.0 -2.0 -3.0 -2
2.4 2.0 3.0 2.0 2
-0.5 -1.0 -0.0 -1.0 0Note -0.0: IEEE floats have a negative zero, which compares equal to 0.0 and prints with its sign. To round to a number of decimal places for display, use fmt.fixed instead.
log
fn log(x: float) floatThe natural logarithm (base e) of x. log(0.0) is minus infinity and the log of a negative number is NaN. For other bases divide: log(x) / log(10.0) is log base 10.
exp
fn exp(x: float) floate raised to the power x; the inverse of log. Large arguments give infinity.
import math
fn main():
print(math.log(math.exp(1.0)), math.exp(0.0), math.log(1000.0) / math.log(10.0))
print(math.log(0.0), math.exp(1000.0))
bad = math.log(-1.0)
print(bad == bad, bad != bad)1.0 1.0 2.9999999999999996
-inf inf
false trueNaN is the one value that is not equal to itself, so x != x tests for it. Print such a value and you see nan (or -nan on some machines).
sin
fn sin(x: float) floatcos
fn cos(x: float) floattan
fn tan(x: float) floatThe sine, cosine, and tangent of an angle in radians. To convert from degrees, multiply by pi() / 180.0. There are no inverse functions (asin, atan2, ...) or hyperbolic ones; call C's libm through extern if you need them (see Calling C).
pi
fn pi() floatThe constant π, 3.141592653589793. It is a function because Tern has no global constants.
import math
fn main():
deg = 30.0
rad = deg * math.pi() / 180.0
print(math.sin(rad), math.cos(0.0), math.tan(math.pi() / 4.0))0.49999999999999994 1.0 0.9999999999999999popcount
fn popcount(x: int) intHow many of x's 64 bits are set (a negative number counts its sign bits too: -1 has 64). One CPU instruction; for comparing bit codes (Hamming distance is popcount(a ^ b)), bit sets and hashes. simd.popcount counts 16 bytes at once.
import math
fn main():
print(math.popcount(0b1011), math.popcount(-1), math.popcount(0xF0 ^ 0x3C))3 64 4A complete example
Summary statistics for a list of readings, and the approximate distance between two points on Earth (the equirectangular approximation, accurate to well under 1% at city scale):
import math
import fmt
fn mean(xs: [float]) float:
total = 0.0
for x in xs:
total += x
return total / float(len(xs))
fn stddev(xs: [float]) float:
m = mean(xs)
sq = 0.0
for x in xs:
sq += math.pow(x - m, 2.0)
return math.sqrt(sq / float(len(xs)))
fn radians(deg: float) float:
return deg * math.pi() / 180.0
fn distance_km(lat1: float, lon1: float, lat2: float, lon2: float) float:
x = radians(lon2 - lon1) * math.cos(radians((lat1 + lat2) / 2.0))
y = radians(lat2 - lat1)
return 6371.0 * math.sqrt(x * x + y * y)
fn main():
temps = [21.5, 23.0, 19.8, 25.1, 22.4]
print("mean", fmt.fixed(mean(temps), 2), "stddev", fmt.fixed(stddev(temps), 2))
km = distance_km(51.5074, -0.1278, 48.8566, 2.3522)
print("London to Paris:", int(math.round(km)), "km")
print("rounded up to 50:", int(math.ceil(km / 50.0)) * 50, "km")mean 22.36 stddev 1.74
London to Paris: 344 km
rounded up to 50: 350 km