Python Math With Examples

In this tutorial, we will learn about Python Math module and its functions. In the previous tutorial, we learned about Python Matrix.

Python Math

Python Math module provides access to the mathematical functions defined by the C standard. So, we can do many complex mathematical operations with the help of the Python Math functions. The tutorial is designed with some basic functions and examples of math module. Let’s get started.

Python Math Functions – floor(), ceil(), fabs(x)

Python math module is part of the python installation, so we can just import it in our python program and use it.

In this section, we will discuss about these three math module functions. The floor() function is used to get the floor value to the given number. Similarly ceil() function is used to get the ceiling value of a given number. So, these two functions are used to round the value, either floor value or ceiling value.

fabs() function is used to get the absolute value of the given number. See the example code below.

And the output will be

Python Math exp(), expm1() and log()

Math module exp() function is used to get e^x.

expm1() function returns (e^x)-1. For small value of x, direct calculation of exp(x)-1 may results in significant loss in precision while the expm1(x) can produce output in full precision.

The log() function is used to get the log value. See the example code.

And you will get the output like this

Python Math Trigonometric Functions

All the trigonometric functions are available in python math module, so you can easily calculate them using sin(), cos(), tan(), acos(), asin(), atan() etc functions.

Also you can convert angles from degree to radian and radian to degree. See the example code.

So, in output you will get

Python Math

Python Math sqrt

We can use sqrt(x) function to get the square root of x. Below is a simple example of python math sqrt function.

Output produced by above math sqrt example is:

Python Math PI

Python math module has “pi” as a constant that can be used in mathematical calculations such as area of a circle.

Above python example program will produce following output.

These are some of the basic functions from Python Math module. If you want to know about more functions, then see the official documentation.

By admin

Leave a Reply

%d bloggers like this: