Playground / The math Module: Logs, Roots and Angles

Pick the base, guard the input

The math Module: Logs, Roots and Angles

Interactive lab

Try it: The math Module: Logs, Roots and Angles

What math.log(x), math.log10(x), math.log(x, base), math.sqrt(x) and math.sin / cos / tan really compute: which logarithm base each call uses, why 0 and negative inputs must be checked before the call (ValueError: math domain error), why trigonometric functions need radians, and that math.pi and every result are binary64 approximations (math.log(1000, 10) prints 2.9999999999999996).

How it works

  1. math.log(x) is the natural logarithm (base e); math.log10(x) is base 10; math.log(x, base) computes log(x) / log(base) with two rounded natural logs.
  2. Logarithms need x > 0 and math.sqrt needs x >= 0; otherwise the call raises ValueError: math domain error, so a guard checks the input first.
  3. math.sin, math.cos and math.tan read their argument as radians: convert degrees with degrees / 360.0 * 2 * math.pi.
  4. math.pi is a float value (no parentheses) that approximates pi to about 16 digits, so sin(180 degrees) is 1.2246467991473532e-16, not 0.
  5. Every result is the nearest binary64 value; print shows the shortest repr that reads back as the same float, while the stored value has more digits.

Default run (6 steps): Ready: the program calls math.log10(x). … print(result) shows 3.0.

Simplified: One-call programs over int / float literals you type (|x| up to 1e15). The results come from the browser's IEEE-754 math library: math.sqrt and the radians arithmetic are identical to CPython; log / sin / cos / tan match CPython 3.12 (Windows) exactly for about 91% of the tested inputs and are within 2 units in the last place otherwise, because C math libraries differ in the last bit. Error messages are CPython 3.12's (3.14 says 'expected a positive input').

Educational simulation

Loading the simulation…