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

featured Image

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

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *