Guidelines for coding simple math in Python

I need to do simple math calculations in Python 2.7 with sums, subtractions, divisions, multiplications, sums over lists of numbers, etc.

I want to write elegant, bulletproof and efficient code, but I must admit that I was confused by several things, for example:

  • If I have 1/(N-1)*x in my equation, I should just encode 1/(N-1)*x or possibly 1.0/(N-1)*x , 1.0/(N-1.0)*x or any other combination of them?
  • for division, should I use // or / with from __future__ import division ?
  • What methods, such as "using math.fsum() to concatenate a list of floats", are there?
  • Should I assume that the input numbers are float or do the conversion just in case (perhaps a risk of performance degradation in many float(x) operations)?

So what are the best code writing methods for simple math calculations in Python which

  • Elegant / Pythonic,
  • effective
  • bulletproof problems like uncertainty about exact input types (float vs integer)?
+4
source share
2 answers
  • If you are using Python 2.7, ALWAYS use from __future__ import division . It removes a hell of a lot of confusion and mistakes.

    With this, you will never have to worry if division is float or not, / will always be float, and // will always be int.

  • You must convert your input using float() . You will do this only once, and it will not be a great success.

  • I would get the sum of the list of such floats: sum(li, 0.0) , but if accuracy is required, use math.fsum , which is specially created for this.

  • And finally, your final expression was confused. Did you mean 1/((N-1)*x) or (1/(N-1))*x ? In the first case, I will write it as 1 / (x * (N-1)) , and in the second case, x / (N-1) . Both suggest a separation of style 3.x.

Also, look at numpy if you need real performance.

+13
source

If you need excellent performance for numeric code in Python, you should consider PyPy. Numpy and scipy are convenient for working with arrays, and they give good performance if you use the linear algebra algorithms that they provide. But if your numerical operations are in pure Python code, PyPy can significantly improve performance. I have seen acceleration above 20 times. And when you use PyPy, the best way to write your math expressions is the easiest way. It optimizes your code better than you could, so make it as simple and easy to read as possible.

+2
source

Source: https://habr.com/ru/post/1388578/


All Articles