Numeric Functions¶
Let us understand some of the common numeric functions we use with Python as programming language. We have functions even for standard operators such as +
, -
, `,
/` under a library called as operator. However, we use operators more often than functions.
add
for+
sub
for-
mul
for*
truediv
for/
- We can use
pow
for getting power value. - We also have
math
library for some advanced mathematical operations. - Also, we have functions such as
min
,max
to get minimum and maximum of the numbers passed.
- We can use
In [1]:
4 + 5
Out[1]:
9
In [2]:
5 % 4
Out[2]:
1
- We can also perform arithmetic operations using operator.
- It have functions such as
add
,sub
,mul
andtruediv
.
In [3]:
import operator
from operator import add, sub, mul, truediv
In [4]:
add?
Signature: add(a, b, /) Docstring: Same as a + b. Type: builtin_function_or_method
In [5]:
add(4, 5)
Out[5]:
9
In [6]:
truediv(4, 5)
Out[6]:
0.8
In [7]:
from operator import mod
mod(5, 4)
Out[7]:
1
In [8]:
pow(2, 3) # This is also available under math library
Out[8]:
8
In [9]:
pow?
Signature: pow(base, exp, mod=None) Docstring: Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form. Type: builtin_function_or_method
math
provides several important functions which are useful on regular basis.- Here are some of the important functions from
math
.pow
ceil
– get next integer to the passed decimal value.floor
– get prior integer to the passed decimal value.round
– it is not frommath
module and it is typically used to get prior or next integer. It will give us prior integer if the decimal up to.5
. If the decimal is greater than.5
, thenround
will return next integer.
In [10]:
import math
In [11]:
math.pow?
Signature: math.pow(x, y, /) Docstring: Return x**y (x to the power of y). Type: builtin_function_or_method
In [12]:
math.ceil(4.4)
Out[12]:
5
In [13]:
math.floor(4.7)
Out[13]:
4
In [14]:
round(4.4)
Out[14]:
4
In [15]:
round(4.7)
Out[15]:
5
In [16]:
round(4.5)
Out[16]:
4
In [17]:
round(4.662, 2) # You can also round a decimal to desired number of decimal places.
Out[17]:
4.66
In [18]:
math.sqrt(2)
Out[18]:
1.4142135623730951
In [19]:
math.pow(2, 3)
Out[19]:
8.0
- We can use
min
to get minimum of passed numbers. You can pass as many numbers as you want.
In [20]:
min?
Docstring: min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument. Type: builtin_function_or_method
In [21]:
min(2, 3)
Out[21]:
2
- We can use
max
to get maximum of passed numbers. You can pass as many numbers as you want.
In [22]:
max(2, 3, 5, 1)
Out[22]:
5