Numpy Constants

NumPy constants are the predefined fixed values used for mathematical calculations.

For example, np.pi is a mathematical constant that returns the value of pi (π), i.e. 3.141592653589793.

Using predefined constants makes our code concise and easier to read.

We'll discuss some common constants provided by Numpy library.


Numpy Constants

In Numpy, the most commonly used constants are pi and e.

np.pi

np.pi is a mathematical constant that returns the value of pi(π) as a floating point number. Its value is approximately 3.141592653589793.

Let's see an example.

import numpy as np

radius = 2
circumference = 2 * np.pi * radius
print(circumference)

Output

12.566370614359172

Here, the np.pi returns the value 3.141592653589793, which calculates the circumference.

Instead of the long floating point number, we used the constant np.pi. This made our code look cleaner.

Note: As pi falls under the Numpy library, we need to import and access it with np.pi.


np.e

np.e is widely used with exponential and logarithmic functions. Its value is approximately 2.718281828459045.

Let's see an example.

import numpy as np

y = np.e

print(y)

Output

2.718281828459045

In the above example, we simply printed the constant np.e. As we can see, it returns its value 2.718281828459045.

However, this example makes no sense because that's not how we use the constant e in real life.

We usually use the constant e with the function exp(). e is the base of exponential function, exp(x), which is equivalent to e^x.

Let's see an example.

import numpy as np

x = 1
y = np.exp(x)

print(y)

Output

2.718281828459045

As you can see, we got the same output like in the previous example. This is because

np.exp(x) 

is equivalent to

np.e ^ x

The value of x is 1. So, np.e^x returns the value of the constant e.


Arithmetic Operations with Numpy Constants and Arrays

We can use arithmetic operators to perform operations such as addition, subtraction, and division between a constant and all elements in an array.

Let's see an example.

import numpy as np

array1 = np.array([1, 2, 3])

# add each array element with the constant pi
y = array1 + np.pi

print(y)

Output

[4.14159265 5.14159265 6.14159265]

In this example, the value 3.141592653589793 (π) is added with each element of array1.