[SciPy-User] Use of numpy functions instead builtins

Anne Archibald peridot.faceted at gmail.com
Sat Apr 3 07:15:23 EDT 2010


On 3 April 2010 06:02, Florian Lindner <mailinglists at xgm.de> wrote:
> Hello,
> I've code that have a lot longer formulas like this on:
>
> tan_theta = ( 2 * (1/tan(sa))*(Ma**2*sin(sa)**2-1)) / ( 2+Ma**2 * (self.f_prop.kappa+1 - 2 * sin(sa)**2) )
>
> all variables are scalars so it works fine with the stuff I get from the math package. Since I"m using scipy anyway in my app I wonder if there is any advantage using the numpy math functions (sin, cos, ..., exp, power). Is there any advantage using them over the python bultins?

The short answer is yes, you should use the numpy versions.

The chief advantage, for you, is that your functions will work on
whole arrays of numbers:
In [1]: np.exp([0,1,2,3])
Out[1]: array([  1.        ,   2.71828183,   7.3890561 ,  20.08553692])

Beyond the simple convenience of not having to write loops, this is
usually much faster than looping over the elements, and for simple
scalar formulas, you get it more or less for free.

There may be other advantages to using the functions in scipy, in
particular; for example, scipy's cosine function works on complex
numbers, and scipy provides a square root that returns complex numbers
when given negative inputs. The numpy functions may also be cleaner
about handling infinities and not-a-number inputs (that is, failing
gracefully when roundoff error becomes overwhelming). But really, the
vectorization is the key advantage.

Anne

> Thanks,
>
> Florian
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>



More information about the SciPy-User mailing list