# Tutorial by Examples

## Rounding: round, floor, ceil, trunc

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) ...

## Logarithms

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, ...

## Copying signs

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 ...

## Trigonometry

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...

## Constants

math modules includes two commonly used mathematical constants. math.pi - The mathematical constant pi math.e - The mathematical constant e (base of natural logarithm) &gt;&gt;&gt; from math import pi, e &gt;&gt;&gt; pi 3.141592653589793 &gt;&gt;&gt; e 2.718281828459045 &gt;&gt;&gt; P...

## Imaginary Numbers

Imaginary numbers in Python are represented by a &quot;j&quot; or &quot;J&quot; trailing the target number. 1j # Equivalent to the square root of -1. 1j * 1j # = (-1+0j)

## Infinity and NaN ("not a number")

In all versions of Python, we can represent infinity and NaN (&quot;not a number&quot;) as follows: pos_inf = float('inf') # positive infinity neg_inf = float('-inf') # negative infinity not_a_num = float('nan') # NaN (&quot;not a number&quot;) In Python 3.5 and higher, we can also us...

## Pow for faster exponentiation

Using the timeit module from the command line: &gt; python -m timeit 'for x in xrange(50000): b = x**3' 10 loops, best of 3: 51.2 msec per loop &gt; 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...

## Complex numbers and the cmath module

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