I started exploring python and was trying to do some calculation with $\pi$. Here's how I got $\pi$:
import math as m
m.pi
But someone suggested using numpy instead of math:
import numpy as np
np.pi
my question is, what is the difference between these two, and is there certain circumstances what we should choose to use one instead of another?
The short answer:
use math if you are doing simple comutations with only with scalars (and no lists or arrays).
Use numpy if you are doing scientific computations with matrices, arrays, or large datasets.
The long answer:
math is part of the standard python library. It provides functions for basic mathematical operations as well as some commonly used constants.
numpy on the other hand is a third party package geared towards scientific computing. It is the defacto package for numerical and vector operations in python. It provides several routines optimized for vector and array computations as a result, is a lot faster for such operations than say just using python lists. See http://www.numpy.org/ for more info.
math
is a built-in library that is shipped with every version of Python. It is used to perform math on scalar data, such as trigonometric computations.
numpy
is an external library. It means you have to install it, after you have already installed Python
. It is used to perform math on arrays, and also linear algebra on matrix.
Other scientific libraries also define pi
, like scipy
. It is common way not to import math library when you need functions that are only present in numpy
or scipy
.
If you only need to access pi
, you should use the math
library.
Moreover, to keep your program light, you should stick with math library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With