I need to perform simple mathematical calculations in Python 2.7 with sums, subtractions, divisions, multiplications, sums over lists of numbers etc.
I want to write elegant, bullet-proof, and efficient code but I must admit I got confused by several things, for example:
- if I have
1/(N-1)*xin my equation should I just code1/(N-1)*xor maybe1.0/(N-1)*x,1.0/(N-1.0)*xor any other combination of these? - for division, should I use
//or/withfrom __future__ import division? - what practices such as “using
math.fsum()for concatenating a list of floats” are out there? - should I assume that input numbers are float or do the conversion just in case (maybe risking drop of efficiency on many
float(x)operations)?
So what are the best practices for writing a code for simple mathematical calculations in Python that is
- elegant/Pythonic,
- efficient,
- bullet-proof to issues like uncertainty in exact number type of input data (float vs integer) ?
If you use Python 2.7, ALWAYS use
from __future__ import division. It removes a hell of a lot confusion and bugs.With this you should never have to worry if a division is a float or not,
/will always be a float and//will always be an int.You should convert your input with
float(). You will do it only once, and it won’t be much of a performance hit.I would get the sum of a list of floats like this:
sum(li, 0.0), but if precision is required, usemath.fsumwhich is specifically created for this.And finally, your final statement was confusing. Did you mean
1/((N-1)*x)or(1/(N-1))*x? In the first case I would write it as1 / (x * (N-1))and in the second casex / (N-1). Both assume 3.x style division.Also, look into numpy if you want some real performance.