Math Module

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

Note that we use `j` (or `J`) and not `i`.

We must use `1j` since `j` would be the name of a variable rather than a numeric literal.

We have the `real` part and the `imag` (imaginary) part, as well as the complex `conjugate`:

The built-in functions `abs` and `complex` are also part of the language itself and don't require any import:

The `complex` function can take a string, but it can't have spaces:

But for most functions we do need the module, for instance `sqrt`:

Naturally the behavior of `sqrt` is different for complex numbers and real numbers. In non-complex `math` the square root of a negative number raises an exception:

Functions are provided to convert to and from polar coordinates:

The mathematical field of complex analysis is beyond the scope of this example, but many functions in the complex plane have a "branch cut", usually along the real axis or the imaginary axis. Most modern platforms support "signed zero" as specified in IEEE 754, which provides continuity of those functions on both sides of the branch cut. The following example is from the Python documentation:

The `cmath` module also provides many functions with direct counterparts from the `math` module.

In addition to `sqrt`, there are complex versions of `exp`, `log`, `log10`, the trigonometric functions and their inverses (`sin`, `cos`, `tan`, `asin`, `acos`, `atan`), and the hyperbolic functions and their inverses (`sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`). Note however there is no complex counterpart of `math.atan2`, the two-argument form of arctangent.

The constants `pi` and `e` are provided. Note these are `float` and not `complex`.

The `cmath` module also provides complex versions of `isinf`, and (for Python 3.2+) `isfinite`. See "Infinity and NaN". A complex number is considered infinite if either its real part or its imaginary part is infinite.

Likewise, the `cmath` module provides a complex version of `isnan`. See "Infinity and NaN". A complex number is considered "not a number" if either its real part or its imaginary part is "not a number".

Note there is no `cmath` counterpart of the `math.inf` and `math.nan` constants (from Python 3.5 and higher)

Python 3.x3.5

In Python 3.5 and higher, there is an `isclose` method in both `cmath` and `math` modules.

Python 3.x3.5

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)

Python 3.5 and higher have constants for infinity and NaN ("not a number"). The older syntax of passing a string to `float()` still works.

Python 3.x3.5

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

Imaginary Numbers

Imaginary numbers in Python are represented by a "j" or "J" trailing the target number.

Infinity and NaN ("not a number")

In all versions of Python, we can represent infinity and NaN ("not a number") as follows:

In Python 3.5 and higher, we can also use the defined constants `math.inf` and `math.nan`:

Python 3.x3.5

The string representations display as `inf` and `-inf` and `nan`:

We can test for either positive or negative infinity with the `isinf` method:

We can test specifically for positive infinity or for negative infinity by direct comparison:

Python 3.2 and higher also allows checking for finiteness:

Python 3.x3.2

Comparison operators work as expected for positive and negative infinity:

But if an arithmetic expression produces a value larger than the maximum that can be represented as a `float`, it will become infinity:

However division by zero does not give a result of infinity (or negative infinity where appropriate), rather it raises a `ZeroDivisionError` exception.

Arithmetic operations on infinity just give infinite results, or sometimes NaN:

NaN is never equal to anything, not even itself. We can test for it is with the `isnan` method:

NaN always compares as "not equal", but never less than or greater than:

Arithmetic operations on NaN always give NaN. This includes multiplication by -1: there is no "negative NaN".

Python 3.x3.5

There is one subtle difference between the old `float` versions of NaN and infinity and the Python 3.5+ `math` library constants:

Python 3.x3.5

Logarithms

`math.log(x)` gives the natural (base `e`) logarithm of `x`.

`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, use `math.log1p`, which evaluates the natural logarithm of 1 plus the argument:

`math.log10` can be used for logs base 10:

Python 2.x2.3.0

When used with two arguments, `math.log(x, base)` gives the logarithm of `x` in the given `base` (i.e. `log(x) / log(base)`.

Pow for faster exponentiation

Using the timeit module from the command line:

The built-in `**` operator often comes in handy, but if performance is of the essence, use math.pow. Be sure to note, however, that pow returns floats, even if the arguments are integers:

Rounding: round, floor, ceil, trunc

In addition to the built-in `round` function, the `math` module provides the `floor`, `ceil`, and `trunc` functions.

Python 2.x2.7

`floor`, `ceil`, `trunc`, and `round` always return a `float`.

`round` always breaks ties away from zero.

Python 3.x3.0

`floor`, `ceil`, and `trunc` always return an `Integral` value, while `round` returns an `Integral` value if called with one argument.

`round` breaks ties towards the nearest even number. This corrects the bias towards larger numbers when performing a large number of calculations.

Warning!

As with any floating-point representation, some fractions cannot be represented exactly. This can lead to some unexpected rounding behavior.

Warning about the floor, trunc, and integer division of negative numbers

Python (and C++ and Java) round away from zero for negative numbers. Consider:

Trigonometry

Calculating the length of the hypotenuse

All `math` functions expect radians so you need to convert degrees to radians:
Apart from the `math.atan` there is also a two-argument `math.atan2` function, which computes the correct quadrant and avoids pitfalls of division by zero: