How to use Pi in Python? (math and numpy module)


How to use Pi in Python? (math and numpy module)

In this article, we will learn about Pi in Python and how to use it in a python program.

Pi (π) is a mathematical constant that is defined as the ratio of a circle's circumference to its diameter.

In Python we can use two modules to use Pi:

  1. math module
  2. numpy module

Using math module

To use Pi (π) in python, we have to import math module and use the math.pi method. It will return the value of pi i.e 3.141592653589793.

The math is the in-built module in python to perform mathematical tasks. It provides different set of methods and constants to work with mathematical operations.

Example:

import math

print(math.pi)

Output:

3.141592653589793

It returns a float value of the Pi constant.

Using Numpy module

We can also use the numpy module to use Pi in Python.

Numpy is a python library that has lots of high-level mathematical functions to perform different math operations.

It also provides us with the numpy.pi method, which can be used to work with Pi in our python program.

To use numpy.pi, we have to import the numpy module first in our program.

Example:

import numpy as np

print(np.pi)

Output:

3.141592653589793

It will also return a floating value of the constant Pi.

Note:

If numpy is not installed in your computer, use pip install numpy command to install and then import it into your project.

Conclusion:

Here, we learned how to use Pi using two different methods in Python i.e using math.pi and numpy.pi method.

The math module is in-built in python, however, to use the Numpy module we have to install it using pip.


Other Articles You'll Also Like:

Find square root of negative number using python

Square a number in Python (3 ways)

Python Bitwise XOR Operator and its Uses