Hi… I’m starting to learn Python to do numerical computations. I noticed that one can use a useful module called “math” to work with many elementary functions. However, the Python code gets a bit long if multiple elementary functions are needed due to the use of the phrase math. before each elementary function like math.log and math.sin, etc. Is there a way to eliminate math. and work with the elementary functions as normal? This can significantly simplify the appearance of the code.
It’s a bit unclear, but it sounds like you want to be able to use
sin(foo) without needing to qualify it as
math.sin(foo)? If so, you just need to do
from math import sin
Thanks Kevin. Is there a single command to do this will all elementary functions instead of just sin? Like from math import all elementary functions.
math module doesn’t distinguish “elementary” functions from anything else. You can import and set multiple names at once, by listing them separated with commas:
from math import sin, cos, tan
Or you can import and set every name that is available:
from math import *
Keep in mind that there are a lot of these, and there is always the risk that something you didn’t expect interferes with something you wanted to use as your own variable (function, class, etc.) name.
I believe you’re the poster who is coming from MATLAB. I highly encourage you to look at NumPy, which is the primary numeric package in Python, and which will probably be most similar to what you are used to in MATLAB. For many of the other things you are used to, SciPy will get you a long way, and scikits are somewhat like MATLAB toolboxes (scikit-learn and scikit-image are two big ones).
I would go ahead and get used to using namespaces instead of importing a lot of things into the current module. It is very common to start with:
import numpy as np
And then use
np.cos. It’s three extra characters per call, but once you finish tearing your hair out trying to understand a traceback and find that the problem ultimately boiled down to importing
math in one module and
numpy in another, those characters will start feeling cheaper.
A very useful doc for making the transition: NumPy for MATLAB users — NumPy v1.25 Manual
Probably the biggest difference in linear algebra is that vectors in numpy are one-dimensional, and are not inherently column or row vectors.
Yes Chris, I’m the one just arriving from a long journey with MATLAB. Your answer is very detailed and informative. Thanks a lot.
A quick alternative is
import math as m. Then
...import * is meant for quick interactive use. For files, it disables linters looking for unused variables.
Thanks Terry. Looks convenient.