NB: Numbers

Programming for Data Science

Built-in Functions

Python has many built-in mathematical functions for numbers.

pow() Power

\(2\) raised to \(3 = 8\)

pow(2,3)
8

abs() Absolute value

Returns \(2\), the absolute value of its argument.

abs(-2)
2

round() Round

Rounding up or down its argument (to closest whole number).

Rounds up to \(3.0\).

round(2.8)
3

Rounds down to \(1.0\).

round(1.1)
1

You can specify how many decimal places to round to as well.

round(5.36958211, 2)
5.37

Math library functions

Python’s Math library contains many other functions to perform mathematical operations.

See the Python docs on the math library for more information.

First, we import the library like so:

import math

We’ll learn more about importing libraries into your programs later in the course.

math.sqrt() Square root

math.sqrt(12)
3.4641016151377544
print(math.floor(2.5)) # returns largest whole number less than the argument
print(math.floor(2.9))
print(math.floor(2.1))
2
2
2

math.log()

math.log(100, 10)
2.0
math.log(256, 2)
8.0

The Random library

Python has a library to help you generate random numbers.

Random number generators are an essential part of any data scientist’s toolkit.

See random — Generate pseudo-random numbers for more information on the library.

import random

random.random()

Using random() will return a number between \(0\) and \(1\).

print(random.random())
0.605894272418689

random.randint()

We may specify a range in the parentheses.

This will return a random integer in the range \(1\) to \(100\) inclusive.

print(random.randint(1,100))
18