When trying to solve an optimization problem, I was constantly getting:
RuntimeWarning: divide by zero encountered in divide
Although analitically writing 1/x and x^(-1) are the same thing, re-writing my function by substituting each division as shown solved my problem.
I was curious to know what makes it different for a computer to compute either a division or an exponentiation.
EDIT:
I am solving a physical problem involving nanometric scales. The complete error I was obtaining is:
RuntimeWarning: divide by zero encountered in divide
term = alpha / w
where alpha is some constant and w>0 is a length. The values of w that I am expecting are of the order of 1e-9 or smaller, and alpha is of the order of 0.1.
Nevertheless, the actual problem IS solved. I am actually surprised such a simple change in the code solved it all, and thus the question.
EDIT 2:
I solved the problem by writing:
term = alpha * w**(-1)
I do know ** equals to exponentiation in Python.
This is your problem:
>>> alpha = 1
>>> w = 2
>>> term = alpha/w
>>> term
0
>>> term = alpha * w **(-1)
>>> term
0.5
>>>
>>> term = float(alpha)/w
>>> term
0.5
In the first example, you are doing integer division which rounds to 0. In the second example you are implicitly converting to float by performing exponentiation. The third example shows that you can get the correct result with division by converting either value to a float