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:
1/(N-1)*x in my equation should I just code 1/(N-1)*x or maybe 1.0/(N-1)*x, 1.0/(N-1.0)*x or any other combination of these?// or / with from __future__ import division?math.fsum() for concatenating a list of floats" are out there?float(x) operations)? So what are the best practices for writing a code for simple mathematical calculations in Python that is
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, use math.fsum which 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 as 1 / (x * (N-1)) and in the second case x / (N-1). Both assume 3.x style division.
Also, look into numpy if you want some real performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With