Python Math

Math


  Machine Learning in Python

Contents

Introduction

Since we will be dealing with probability and statistics very much in Data Science and Machine learning, we suggest that you have a good understanding of the basic math functionality available in Python. Although, we would be tempted to classify this as optional for now, we do recommend this as mandatory for Data Science & Machine learning. Although, the list of contents look huge, you should really be pretty familiar with these already as these are just Python implementations of your high school math.


Basic Math

ceil ()

from math import ceil

i = 3.5
ceil(i)

4

floor ()

from math import floor

i = 3.5
floor (i)

3

trunc ()

Python’s trunc () function looks very similar to the floor () function – but there is a difference. We can observe this difference only when dealing with negative numbers. For example, let’s floor and ceil a negative number and observe what happens.

i = -3.5

floor(i)

-4
i = -3.5

ceil(i)

-3
from math import trunc

i = -3.5
trunc(i)

-3

exp ()

The function exp () calculates the exponential of a value.

rom math import exp

x = 3.5
exp(x)

33.11545195869231

pow ()

You might already have seen the operator or the built-in pow ( ) function that can calculate the power of one integer with another. For example

2 ** 5
32
pow(2,5)
32

math module’s pow ( ) function does exactly the same, except it converts the operands into floating point first and does the calculation.

from math import pow

pow(2,5)

32.0

Here is how the 3 functions compare against each other.

A good example why you should never use

from math import *

sqrt ( )

Calculates the square root of a value.

from math import sqrt

sqrt(100)

10

log ()

In data science, calculating the logarithm of a value is useful for scaling some of the predictors that are at an exponential scale compared to others.

from math import log

log(100)

4.605170185988092

By default the base is ‘e’. If you wanted to calculate the logarithm to the base 10, use

log (100,10)

2.0

Constants

There are a couple of constants that the math module holds for us.


pi

from math import pi

pi

3.141592653589793

e

from math import e

e

2.718281828459045

Challenge – Calculate the area of a circle with a radius of 5.

Solution

r = 5 # say cm
area = pi * ( r **2 )

area

78.53981633974483

Trignometric functions

All of the standard trignometric (sin,cos,tan etc ) and hyperbolic (sinh, cosh, tanh etc ) functions area available in the math module. However, we have to note that the input parameter is always in radians and not in degrees. So, there are functions available to convert them into each other.

  • math.radians (x) – converts x (in degrees) to radians
  • math.degrees (x) – converts x (in radians) to degrees

For example, to calculate sin (90) which is 1, we first convert the degrees to radians and use the sin ( ) function.

from math import radians, sin

degrees = 90
sin(radians(degrees))

1.0

Special functions

fsum ()

We have seen in lists that sum ( ) can add all the numbers in a list. However, when you need a higher floating point accuracy, use the math module’s fsum ( ) module. For example, take the following list with floating point numbers.

height = [0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09]
sum(height)
0.45000000000000007
from math import fsum

fsum(height)

0.45

As you can see, the math module’s fsum has much better accuracy than python’s in-built sum function. fsum basically tracks the sum multiple times in between the iterations to avoid loss of precision. You can view a detailed explanation on Python’s help site here .

gcd ()

gcd stands for greatest common divisor . It is the greatest number that can divide 2 numbers. For example, what is the greatest number that can divide both 20 and 100 – it is 20 ofcourse.

from math import gcd

gcd(20,100)

20

Challenge – Calculate the gcd of two numbers without using the math module’s gcd ( ) function.

code
 
def calc_gcd (i,j) :
    
    # first check the smallest number.
    if i < j :
        smallest = i
    elif j < i :
        smallest = j
    else :
        # both are equal.
        return i
    
    # iterate the divisor until the smallest number.
    # Don't iterate from 0 though - :)
    # smallest + 1 to include itself - it is not included in the range function by default.
    
    for divisor in range (1, smallest + 1) :
        if (i % divisor == 0) and (j % divisor == 0) :
            gcd = divisor
    
    return gcd
# test it 
calc_gcd(20,100)

20

factorial ()

Factorial is the multiplication of an integer and all the positive integers below it. For example,

5 factorial =  5 x 4 x 3 x 2 x 1
            =  120
from math import factorial

factorial(5)

120

Challenge – Calculate the factorial without using the math module’s factorial ( ) function.

def factorial (x) :
    
    if x == 0 : 
        return 1
    
    if x < 0 :
        return undefined
    
    # counter to decrement x and find out all the integers less than x
    y = x
    
    # variable to hold the factorial value
    factorial = 1
    
    while ( y >= 1 ) :
        factorial = factorial * y
        y = y - 1  # decrement to get the next lower integer
    
    return factorial

factorial(5)
120
%d bloggers like this: