The built-in math module collects the numerical functions that the operators of the language do not cover; rounding, roots and logarithms, trigonometry, and the handling of the special values that floating-point arithmetic produces. Like any standard module, it is brought in with import:
import math
print(math.sqrt(16)) // 4
Nearly all of the module’s functions take one number and return one number, and most of them are the familiar functions of the C math library under the same name.
This chapter groups them by purpose and concentrates on the way they are used and on the cases that deserve care. The complete list is given in the Math reference.
Remember that numbers in Teascript are always double-precision floating-point values. There is (currently) no separate integer type, so math.floor returns a number like other, and a function that is documented expecting an integer simply truncates its argument if necessary. Passing anything that is not a number is an error.
Constants
The module provides a few constants as attributes:
| Name | Value |
|---|---|
math.pi | The ratio of the circumference of a circle to its diameter, 3.14159… |
math.tau | Twice pi, the number of radians in a full turn |
math.e | The base of the natural logarithm, 2.71828… |
math.phi | The golden ratio, 1.61803… |
math.infinity | Positive infinity |
math.nan | The value not a number |
math.maxinteger | The largest integer that the interpreter treats as such |
math.mininteger | The smallest one |
The last two are mostly of interest to programs that deal with bit operations or that must be careful about the limits of integer values. They are described again below, with the other special values.
Rounding and Signs
Four functions turn a number with a fractional part into a whole one, and they differ only in the direction the rounding takes. floor goes towards negative infinity, ceil towards positive infinity, trunc towards zero, and round to the nearest whole number, with halves rounded away from zero:
print(math.floor(2.7), math.floor(-2.7)) // 2 -3
print(math.ceil(2.2), math.ceil(-2.2)) // 3 -2
print(math.trunc(2.7), math.trunc(-2.7)) // 2 -2
print(math.round(2.5), math.round(-2.5)) // 3 -3
The difference between floor and trunc only shows with negative numbers, and it can be a source of off-by-one mistakes. When in doubt, think of a number line; floor always moves to the left.
None of them takes a number of decimals. To round to a given number of decimal places, scale, round and scale back:
var price = 3.14159
print(math.round(price * 100) / 100) // 3.14
The function abs returns the absolute value, dropping the sign, and sign returns -1, 0 or 1 according to the sign of its argument, which is handy for deciding a direction:
print(math.abs(-7.5)) // 7.5
print(math.sign(-7.5)) // -1
print(math.sign(0)) // 0
Comparing and Limiting
The functions min and max return the smallest and the largest of their arguments.
They accept any number of values, or a single list of them, which saves unpacking a list that the whole program already has:
print(math.min(4, 9, 2)) // 2
print(math.max([4, 9, 2])) // 9
At least one value is needed, and all of them must be numbers.
The function clamp restricts a number to an interval.
It takes the value, the lower bound and the upper bound, and returns the value itself when it is inside, or the bound that is exceeded otherwise. It is the tool for keeping a quantity within its valid range, such as a volume, a position on the screen, or an index:
print(math.clamp(15, 0, 10)) // 10
print(math.clamp(-3, 0, 10)) // 0
print(math.clamp(7, 0, 10)) // 7
The bounds are expected to be in order.
A last relative is mid, which returns the middle of three numbers, otherwise known as their median, whatever their order:
print(math.mid(9, 1, 4)) // 4
Powers, Roots and Logarithms
Exponentiation has its own operator, **, as seen in the Expressions chapter, and therefore the module has no function for it.
What it provides are the roots and the logarithms.
The function sqrt computes the square root, and exp raises e to a power.
Their inverse is the natural logarithm log, with three variants for different needs: log2 and log10 for the logarithms in base 2 and 10, and log1p, which computes log(1 + x) and is more accurate than writing that expression when x is very small.
print(math.sqrt(2)) // 1.4142135623731
print(math.log2(1024)) // 10
print(math.log10(1000)) // 3
print(math.exp(0)) // 1
To compute the logarithm of a number in any other base, divide the natural logarithms:
function logn(x, base)
{
return math.log(x) / math.log(base)
}
print(logn(81, 3)) // 4
Similarly, a root other than the square one is a power with a fractional exponent, as in 27 ** (1 / 3).
Notice that none of these functions raises an error for an argument outside of its domain. They return the special values that are described later in this chapter; the square root of a negative number is NaN, and the logarithm of zero is negaive infinity.
Trigonometry
The module has the usual trigonometric functions: sin, cos and tan, their inverses asin, acos and atan, and the hyperbolic versions sinh, cosh, tanh, asinh, acosh and atanh.
All of them work in radians, not degrees, with a full turn being math.tau.
print(math.sin(math.pi / 2)) // 1
print(math.cos(0)) // 1
print(math.atan(1) * 4) // 3.1415926535898
Since angles are so often given in degrees, the functions deg and rad convert between the two units. rad takes degrees and returns radians, and deg does the opposide:
print(math.rad(180)) // 3.1415926535898
print(math.deg(math.pi)) // 180
The function atan has a limitation that is worth knowing.
It receives a single ratio, so it cannot tell the angle of (1, 1) from that of (-1, -1), because both have the same ratio. For finding the direction of a point, atan2 takes the two coordinates separately, and gives the right angle in every quadrant. Note however that the vertical coordinate, y, comes first:
print(math.deg(math.atan2(1, 1))) // 45
print(math.deg(math.atan2(-1, -1))) // -135
Because the results of these functions are computed in floating point, they may not always be exact; math.sin(math.pi) is a number extremely close to zero, but not zero. The next section explains what to do about it.
Floating-Point Numbers
Numbers in Teascript have the same limits as the double of C, and any language that follows the same standard, and they have the same surprises. Most decimal fractionals cannot be stored exactly, and so the result of an operation may differ although very slightly from what arithmetic on paper would give:
print(0.1 + 0.2 == 0.3) // false
Because of this, comparing computed float numbers for equality is rarely what is wanted. The usual remedy is to compare them within a small tolerance:
function near(a, b, epsilon = 1e-9)
{
return math.abs(a - b) < epsilon
}
print(near(0.1 + 0.2, 0.3)) // true
print(near(math.sin(math.pi), 0)) // true
Whole numbers are exact up to a large size, so counters, indices and sums of integers are still safe. It is only the fractions, and the numbers beyond that size, that lose precision.
Special Values
Floating-point arithmetic does not fail when an operation has no sensible answer.
It produces a special value instead, and the computation goes on. There are two of them.
Infinity is the result of an overflow or of the logarithm of zero, and it is available as math.infinity, with its negative -math.infinity. It compares as larger than any number, which makes it useful as the starting point of a search for a minimum:
var lowest = math.infinity
for var n in [4, 9, 2]
{
if n < lowest { lowest = n }
}
print(lowest) // 2
Not a Number, math.nan, is the result of an operation that has no value, such as the square root of a negative number.
It has the usual property that it is different from every other number value, including itself, so it cannot be detected with a normal ==. The functions math.isnan and math.isinfinity are made for handling these cases, and, since a NaN that goes unnoticed spreads to every operation that touches it, they are a good way of checking a computation that may have gone wrong:
var x = math.sqrt(-1)
print(math.isnan(x)) // true
print(math.isinfinity(math.log(0))) // true
print(math.isnan(4)) // false
For finer distinctions, classify returns a string describing the kind of number it is given; "normal" for ordinary numbers, "zero", "subnormal" for those close to zero that have lost precision, "infinity" and "nan".
print(math.classify(1.5)) // normal
print(math.classify(0)) // zero
print(math.classify(math.nan)) // nan
Taking Numbers Apart
Two more functions expose the internal representation of a number, which is of interest to programs that need to know its magnitude or build numbers from scratch.
A floating-point number is stored as a mantissa, between 0.5 and 1, multiplied by a power of two.
The function frexp returns both parts as a list, and ldexp puts them back together:
var m, e = math.frexp(48)
print(m, e) // 0.75 6
print(math.ldexp(m, e)) // 48
They are specialized tools of this module, and most programs will never need them.
An Example
The following program receives the three sides of a triangle and describes it; its perimeter, its area, and its three angles in degrees.
The area is calculaed with Heron’s formula, which uses sqrt, and the angles come from the law of cosines, which needs acos, deg and round for the presentation.
If the three lengths cannot form a triangle, the cosine that results is greater than one or less then minus one, and acos answers with NaN.
The program uses isnan to detect that, so it does not have to check the inequality of the sides beforehand.
// triangle.tea
import math
function angle(a, b, c)
{
// the angle opposite to side a, in degrees
return math.deg(math.acos((b * b + c * c - a * a) / (2 * b * c)))
}
function show(label, value)
{
print("${label}: ${math.round(value * 100) / 100}")
}
function describe(a, b, c)
{
var alpha = angle(a, b, c)
if math.isnan(alpha)
{
print("${a}, ${b}, ${c} is not a triangle")
return
}
var s = (a + b + c) / 2
show("perimeter", a + b + c)
show("area", math.sqrt(s * (s - a) * (s - b) * (s - c)))
show("angles", alpha)
show(" ", angle(b, a, c))
show(" ", angle(c, a, b))
}
describe(3, 4, 5)
describe(1, 2, 10)$ tea triangle.tea
perimeter: 12
area: 6
angles: 36.87
: 53.13
: 90
1, 2, 10 is not a triangle
Every result is rounded only when it is shown, and never while it is being calculated, so the small errors of the intermediate steps do not accumulate.
This is a good habit in general; keep the full precision in the computation and round for the output to be shown. And notice that the right angle comes out as exactly 90 only after the rounding. The unrounded value may be off by an amount too small to see, which is the reason why near was the right way of comparing numbers in the previous section.