Tutorial by Examples

The math module contains the math.sqrt()-function that can compute the square root of any number (that can be converted to a float) and the result will always be a float: import math math.sqrt(9) # 3.0 math.sqrt(11.11) # 3.3331666624997918 math.sqrt(Decimal('6.25')) ...
Exponentiation can be used by using the builtin pow-function or the ** operator: 2 ** 3 # 8 pow(2, 3) # 8 For most (all in Python 2.x) arithmetic operations the result's type will be that of the wider operand. This is not true for **; the following cases are exceptions from this rule: B...
The math-module contains another math.pow() function. The difference to the builtin pow()-function or ** operator is that the result is always a float: import math math.pow(2, 2) # 4.0 math.pow(-2., 2) # 4.0 Which excludes computations with complex inputs: math.pow(2, 2+0j) TypeErro...
Both the math and cmath-module contain the Euler number: e and using it with the builtin pow()-function or **-operator works mostly like math.exp(): import math math.e ** 2 # 7.3890560989306495 math.exp(2) # 7.38905609893065 import cmath cmath.e ** 2 # 7.3890560989306495 cmath.exp(2) # (...
The math module contains the expm1()-function that can compute the expression math.e ** x - 1 for very small x with higher precision than math.exp(x) or cmath.exp(x) would allow: import math print(math.e ** 1e-3 - 1) # 0.0010005001667083846 print(math.exp(1e-3) - 1) # 0.0010005001667083846 p...
Supposing you have a class that stores purely integer values: class Integer(object): def __init__(self, value): self.value = int(value) # Cast to an integer def __repr__(self): return '{cls}({val})'.format(cls=self.__class__.__name__, ...
Supplying pow() with 3 arguments pow(a, b, c) evaluates the modular exponentiation ab mod c: pow(3, 4, 17) # 13 # equivalent unoptimized expression: 3 ** 4 % 17 # 13 # steps: 3 ** 4 # 81 81 % 17 # 13 For built-in types using modular exponentiation is only possible...
While the math.sqrt function is provided for the specific case of square roots, it's often convenient to use the exponentiation operator (**) with fractional exponents to perform nth-root operations, like cube roots. The inverse of an exponentiation is exponentiation by the exponent's reciprocal. S...
Even though Python natively supports big integers, taking the nth root of very large numbers can fail in Python. x = 2 ** 100 cube = x ** 3 root = cube ** (1.0 / 3) OverflowError: long int too large to convert to float When dealing with such large integers, you will need to use a custom f...

Page 1 of 1