24 Mathematics
The arithmetic operators are in the language itself (Numbers and Operators). A few
functions sit beside them with no import, and the math
module holds the rest: square roots, rounding, angles, logarithms and
powers of e.
24.1 The functions that need no import
| Written | Gives |
|---|---|
abs(x) |
x without its sign |
min(a, b, ...),
min(xs) |
the smallest of the numbers, or of a list |
max(a, b, ...),
max(xs) |
the largest |
sum(xs) |
the numbers of a list added up |
print(abs(-3), abs(2.5), min(3, 1, 2), max([4, 9, 2]), sum([1.5, 2.5]))3 2.5 1 9 4.0
24.2 The math module
| Written | Takes | Gives |
|---|---|---|
math.pi,
math.e |
float |
|
math.sqrt(x) |
a number, 0 or more | float |
math.floor(x),
ceil, round |
a number | int |
math.sin(a),
cos, tan |
an angle | float |
math.asin(x),
acos |
a number from − 1 to 1 | rad |
math.atan(x) |
a number | rad |
math.atan2(y, x) |
two numbers | rad |
math.exp(x) |
a number | float |
math.log(x),
log2, log10 |
a number above 0 | float |
import math
print(math.sqrt(2.0), math.pi)
print(math.floor(-1.5), math.ceil(1.2), math.round(2.5), math.round(-2.5))
print(math.log(math.e), math.log2(8.0), math.log10(1000.0), math.exp(0.0))1.4142135623730951 3.141592653589793
-2 2 3 -3
1.0 3.0 3.0 1.0
Rounding
floor rounds down, ceil rounds up, and
round goes to the nearest whole number, with a half going
away from zero. All three give an int, because an index or
a register value is usually what is wanted next. To show a number with
two decimals, don’t round it; format it: f"{x:.2f}".
Python’s round sends a half to the nearest even number,
so round(2.5) is 2 and round(3.5) is 4. That
is better for adding up many rounded numbers, and a surprise to nearly
everyone who meets it. Zeno rounds as school taught, as C and Rust do.
(Decision 6.25.)
Logarithms
log is the natural logarithm, with base e, as in C, Python, JavaScript and
Java. log2 and log10 have their bases in their
names. There is no log(x, base): log2(8.0) is
exactly 3, while dividing two natural logarithms gives
3.0000000000000004. (Decision 6.26.)
A number with no answer
The square root of a negative number, or the logarithm of 0, has no
answer, and is a ValueError with the number in its
message:
import math
try {
print(math.sqrt(-1.0))
} except ValueError as e {
print(e.message)
}
print(math.log(0.0))cannot take the square root of -1.0
error: uncaught ValueError: cannot take the logarithm of 0.0
--> main.zeno:7:7
|
7 | print(math.log(0.0))
| ^
C gives a nan, "not a number", which spreads through
every sum it touches and is printed twenty lines later, far from the
line that made it. An error at the line that asked is easier to find.
(Decision 6.27.)
24.3 Angles
Degrees handed to a function that counts in radians is the classic
mistake with angles, and in C it gives a wrong number with no complaint.
In Zeno an angle can carry its unit (Numbers with Units), and the
functions of math read it:
import math
print(math.sin(30 deg), math.sin(0.5 rad), math.sin(0.5))
print(math.cos(180 deg), math.tan(45 deg))0.49999999999999994 0.479425538604203 0.479425538604203
-1.0 0.9999999999999999
A plain number is taken too, and means radians, because that is what
the sine of a number means in mathematics, and signal code is full of
math.sin(2.0 * math.pi * f * t). The sine of 30 degrees is
not exactly 0.5, because a float cannot hold π/6 exactly; Python prints the same
digits.
The functions that give an angle, asin,
acos, atan and atan2, give it in
rad, so the value says what it is. .deg
changes it:
import math
let heading = math.atan2(1.0, -1.0)
print(heading, heading.deg)
print(heading / 1 rad)2.356194490192345 rad 135 deg
2.356194490192345
atan2(y, x) takes y first. It is the angle
of the point (x,y)
seen from the middle, and unlike atan(y / x) it knows which
side of the circle the point is on.
24.4 What is not here
| Elsewhere | In Zeno |
|---|---|
pow(x, y) |
x ** y |
trunc(x) |
int(x) |
fabs(x) |
abs(x) |
degrees(x),
radians(x) |
angle.deg,
angle.rad |
round(x, 2) |
f"{x:.2f}" |
The answers are the C library’s, in every way of running a program: a
compiled program calls sin and log in the C
library, and zeno run reaches the same functions. Two
machines with different C libraries can differ in the last digit of an
answer that is not exact. (Decision 6.28.)
24.5 Five small instruments
This program, from the examples folder of Zeno, is five
pieces of arithmetic that firmware does every day: a compass from a
magnetometer, a thermistor, a level meter in decibels, a capacitor
charging, and a sine table for an 8-bit converter.
examples/instruments.zeno
# Five small instruments, each a few lines of arithmetic that firmware
# does every day. They use the `math` module: angles, logarithms, powers
# of e, and rounding.
#
# zeno run examples/instruments.zeno
import math
# A compass. A magnetometer gives the field along x and along y, and
# `atan2` turns the two into an angle, all the way round. The angle comes
# back in radians and says so; `.deg` changes it, and a heading is
# counted from 0 to 360.
function heading(x: float, y: float) -> deg {
let angle = math.atan2(y, x).deg
if angle < 0 deg {
return angle + 360 deg
}
return angle
}
# A thermistor. Its resistance falls as it warms, along a curve with a
# logarithm in it (the "beta" equation). 10 kohm at 25 degC, beta 3950.
function thermistor(ohms: float) -> float {
let kelvin = 1 / (1 / 298.15 + math.log(ohms / 10000.0) / 3950.0)
return kelvin - 273.15
}
# A level meter. Decibels are twenty times the logarithm, base ten, of
# how many times bigger one voltage is than another.
function decibels(volts: float, reference: float) -> float {
return 20 * math.log10(volts / reference)
}
# A capacitor charging through a resistor: the part of the supply it has
# reached after `seconds`. `tau` is the resistance times the capacitance.
function charged(seconds: float, tau: float) -> float {
return 1 - math.exp(-seconds / tau)
}
# A sine table for a digital-to-analogue converter of eight bits: one
# turn in `steps` steps, each a whole number from 0 to 255.
function sine_table(steps: int) -> list[int] {
var table: list[int] = []
for step in range(steps) {
let angle = step * 360 / steps * 1 deg
table.append(math.round(127.5 + 127.5 * math.sin(angle)))
}
return table
}
print("compass")
let fields = [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [-1.0, 1.0], [-1.0, 0.0], [0.0, -1.0], [3.0, -4.0]]
for field in fields {
let angle = heading(field[0], field[1])
# A format on a quantity is the number's, and the unit follows it.
# The width counts both: six for the number, four for ` deg`.
print(f" x {field[0]:5.1f} y {field[1]:5.1f} heading {angle:10.1f}")
}
print("thermistor")
for ohms in [32650.0, 10000.0, 3603.0, 1070.0] {
print(f" {ohms:8.0f} ohm {thermistor(ohms):6.1f} degC")
}
print("level meter")
for volts in [1.0, 0.5, 0.1, 2.0] {
print(f" {volts:4.1f} V {decibels(volts, 1.0):6.1f} dB")
}
print("capacitor, tau 0.5 s")
for tenths in range(0, 30, 5) {
let seconds = tenths / 10
print(f" after {seconds:.1f} s {100 * charged(seconds, 0.5):5.1f} %")
}
print("sine table")
print(" ", sine_table(16))compass
x 1.0 y 0.0 heading 0.0 deg
x 1.0 y 1.0 heading 45.0 deg
x 0.0 y 1.0 heading 90.0 deg
x -1.0 y 1.0 heading 135.0 deg
x -1.0 y 0.0 heading 180.0 deg
x 0.0 y -1.0 heading 270.0 deg
x 3.0 y -4.0 heading 306.9 deg
thermistor
32650 ohm 0.6 degC
10000 ohm 25.0 degC
3603 ohm 49.9 degC
1070 ohm 85.5 degC
level meter
1.0 V 0.0 dB
0.5 V -6.0 dB
0.1 V -20.0 dB
2.0 V 6.0 dB
capacitor, tau 0.5 s
after 0.0 s 0.0 %
after 0.5 s 63.2 %
after 1.0 s 86.5 %
after 1.5 s 95.0 %
after 2.0 s 98.2 %
after 2.5 s 99.3 %
sine table
[128, 176, 218, 245, 255, 245, 218, 176, 128, 79, 37, 10, 0, 10, 37, 79]
abs, min, max and
sum need no import. math holds
pi, e, sqrt, floor,
ceil, round (half away from zero, giving an
int), the angle functions, exp and three logarithms. Angles
go in with their units, or as radians, and come out in rad.
A number with no answer is a ValueError, never
nan.
Write a function
distancethat takes the fourfloatsx1,y1,x2andy2, and gives the distance between the two points.Make a sine table of 32 entries for a 10-bit converter (0 to 1023).
Work out how many bits are needed to count to a number with
log2andceil. Check it for 255, 256 and 1000.What does
math.asin(1.5)do? Catch it and print the message.