Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for coding simple mathematical calculations in Python

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)*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?
  • for division, should I use // or / with from __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

  1. elegant/Pythonic,
  2. efficient,
  3. bullet-proof to issues like uncertainty in exact number type of input data (float vs integer) ?
like image 716
jan Avatar asked Dec 07 '22 17:12

jan


1 Answers

  1. 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.

  2. You should convert your input with float(). You will do it only once, and it won't be much of a performance hit.

  3. 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.

  4. 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.

like image 143
orlp Avatar answered Apr 30 '23 23:04

orlp