[SciPy-User] Use of numpy functions instead builtins
Sat Apr 3 07:39:12 CDT 2010
On 3 April 2010 07:32, Warren Weckesser <email@example.com> wrote:
> Anne Archibald wrote:
>> On 3 April 2010 06:02, Florian Lindner <firstname.lastname@example.org> wrote:
>>> 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 : np.exp([0,1,2,3])
>> Out: 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.
> On the other hand, the numpy versions are *much* slower, so if all the
> variables are scalars and performance is an issue, you might prefer the
> standard math functions.
Just to be clear: if you're calling the functions on scalars, the
numpy functions are slower than the python library functions. This is
because they do a certain amount of marshaling and type conversion. In
the very common case that you want to apply the same function to many
data points, if you pass those data points as an array to a numpy
function - or to your function that uses numpy functions - you will
not only avoid having to write a loop, the code will run much faster.
>>> SciPy-User mailing list
>> SciPy-User mailing list
> SciPy-User mailing list
More information about the SciPy-User