Tutorial by Examples

In addition to the built-in round function, the math module provides the floor, ceil, and trunc functions. x = 1.55 y = -1.55 # round to the nearest integer round(x) # 2 round(y) # -2 # the second argument gives how many decimal places to round to (defaults to 0) round(x, 1) ...
math.log(x) gives the natural (base e) logarithm of x. math.log(math.e) # 1.0 math.log(1) # 0.0 math.log(100) # 4.605170185988092 math.log can lose precision with numbers close to 1, due to the limitations of floating-point numbers. In order to accurately calculate logs close to 1, ...
In Python 2.6 and higher, math.copysign(x, y) returns x with the sign of y. The returned value is always a float. Python 2.x2.6 math.copysign(-2, 3) # 2.0 math.copysign(3, -3) # -3.0 math.copysign(4, 14.2) # 4.0 math.copysign(1, -0.0) # -1.0, on a platform which supports signed zero ...
Calculating the length of the hypotenuse math.hypot(2, 4) # Just a shorthand for SquareRoot(2**2 + 4**2) # Out: 4.47213595499958 Converting degrees to/from radians All math functions expect radians so you need to convert degrees to radians: math.radians(45) # Convert 45 degrees t...
math modules includes two commonly used mathematical constants. math.pi - The mathematical constant pi math.e - The mathematical constant e (base of natural logarithm) >>> from math import pi, e >>> pi 3.141592653589793 >>> e 2.718281828459045 >>> P...
Imaginary numbers in Python are represented by a "j" or "J" trailing the target number. 1j # Equivalent to the square root of -1. 1j * 1j # = (-1+0j)
In all versions of Python, we can represent infinity and NaN ("not a number") as follows: pos_inf = float('inf') # positive infinity neg_inf = float('-inf') # negative infinity not_a_num = float('nan') # NaN ("not a number") In Python 3.5 and higher, we can also us...
Using the timeit module from the command line: > python -m timeit 'for x in xrange(50000): b = x**3' 10 loops, best of 3: 51.2 msec per loop > python -m timeit 'from math import pow' 'for x in xrange(50000): b = pow(x,3)' 100 loops, best of 3: 9.15 msec per loop The built-in ** operato...
The cmath module is similar to the math module, but defines functions appropriately for the complex plane. First of all, complex numbers are a numeric type that is part of the Python language itself rather than being provided by a library class. Thus we don't need to import cmath for ordinary arith...

Page 1 of 1