Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between import numpy and import math [duplicate]

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?

like image 505
PiCubed Avatar asked Jan 14 '17 08:01

PiCubed


2 Answers

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.

like image 97
Xero Smith Avatar answered Sep 20 '22 14:09

Xero Smith


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.

like image 34
Guillaume Jacquenot Avatar answered Sep 21 '22 14:09

Guillaume Jacquenot