12

I started exploring python and was trying to do some calculation with pi. Here's how I got it:

import math as m
m.pi

But someone suggested using numpy instead of math:

import numpy as np
np.pi

What is the difference between these two, and are there certain circumstances where we should choose to use one instead of the other?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
PiCubed
  • 375
  • 2
  • 5
  • 11

2 Answers2

17

The short answer:

  • Use math if you are doing simple computations with only 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 python standard 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 and as a result, is a lot faster for such operations than say, just using python lists. See the website for more info.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Xero Smith
  • 1,968
  • 1
  • 14
  • 19
9

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. That 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 matrices.

Other scientific libraries also define pi, like scipy. It is common 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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
  • 2
    Just use `numpy` all the time. – NoName Jan 12 '20 at 20:33
  • 2
    @NoName I was on your side for years, but a friend just convinced me that one advantage of `math` over `numpy` would be to reduce your pyinstaller exe by like 200 MB. – Guimoute Nov 04 '20 at 20:45
  • @NoName For convenience, yeah, might as well, but for specific applications it might make more sense to use `math`. Hypothetically, say you want the square root of a positive float, but by some error it ends up as a negative number of a list of complex numbers. `numpy` will go ahead (except a warning for the negatives), but `math` will raise errors. – wjandrea Feb 26 '23 at 16:47