Exponentation

suggest change
a, b = 2, 3

(a ** b)               # = 8
pow(a, b)              # = 8

import math
math.pow(a, b)         # = 8.0 (always float; does not allow complex results)

import operator
operator.pow(a, b)     # = 8

Another difference between the built-in pow and math.pow is that the built-in pow can accept three arguments:

a, b, c = 2, 3, 2

pow(2, 3, 2)           # 0, calculates (2 ** 3) % 2, but as per Python docs,
                       #    does so more efficiently

Special functions

The function math.sqrt(x) calculates the square root of x.

import math
import cmath
c = 4
math.sqrt(c)           # = 2.0 (always float; does not allow complex results)
cmath.sqrt(c)          # = (2+0j) (always complex)

To compute other roots, such as a cube root, raise the number to the reciprocal of the degree of the root. This could be done with any of the exponential functions or operator.

import math
x = 8
math.pow(x, 1/3) # evaluates to 2.0
x**(1/3) # evaluates to 2.0

The function math.exp(x) computes e ** x.

math.exp(0)  # 1.0
math.exp(1)  # 2.718281828459045 (e)

The function math.expm1(x) computes e ** x - 1. When x is small, this gives significantly better precision than math.exp(x) - 1.

math.expm1(0)       # 0.0

math.exp(1e-6) - 1  # 1.0000004999621837e-06
math.expm1(1e-6)    # 1.0000005000001665e-06
# exact result      # 1.000000500000166666708333341666...

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents