Mathematical functions

Contents

Mathematical functions#

  • introductory paragraph

  • make the link with the Laby exercises; especially when we talk about modularity

  • more practice exercises; including with Laby?

  • the spiel on modularity is possibly redundant with the course on functions

In the previous sheet, we saw arithmetic operations; we can use

more complex mathematical functions that already exist in Python.

To access them, we start by importing the math module: this is a

Python file that contains reusable code, we will come back to this later.

import math

Here are some examples of function calls that you can test by modifying the

values in parentheses.

The square root function:

math.sqrt(4)
2.0

The exponential function:

math.exp(2)
7.38905609893065

Trigonometric functions (in radians):

math.sin(3.14)
0.0015926529164868282
math.cos(0)
1.0

For the power function, note that the order of the values in parentheses is important:

math.pow(5, 2)
25.0
math.pow(2, 5)
32.0

The factorial function, which only works when given an integer:

math.factorial(3)
6

Conclusion#

Several important things are worth noting:

  • The presence of import math at the beginning: this is necessary to use the module of pre-existing mathematical functions.

  • These functions (like math.cos, math.sqrt, math.pow, etc.) are already programmed: we know what they calculate, but not how they do it. And that’s normal: we don’t need to know how they are implemented to use them effectively!

  • You have to pay attention to the order of the values between the parentheses: for example in math.pow(x, y), we calculate x to the power of y

  • …and also to the type of these values: some functions require a floating point number (float) or an integer (int), and the correct type is important to avoid errors.

We will see later how to write our own functions.