Python – divide by zero encountered in double_scalars for derivative calculations

numpypythonpython-2.7

I am learning to use python for numerical computations. I want to calculate derivative using the central difference method. When I try to set my interval dx, python takes it to 0 even though the actual value is (1/6)? Any way to get rid of this?

Here's the code:

import numpy as np
import matplotlib.pyplot as plt

a = 0
b = 1
n = 7
dx = np.float(((b-a)/n))
x = np.linspace(a,b,n)
xpp = np.zeros(n)

for ii in range(1,n-1):
    xpp[ii] = (x[ii-1] - 2*x[ii+1] + x[ii+1])/(pow(dx,2))
print xpp

Best Answer

In Python 2.7, integer division does floor:

>>> a = 0
>>> b = 1
>>> n = 7
>>> (b - a) / n
0

=> dx become 0.0 => Inside for loop body, it is used as a dividor. (02 = 0)

You need to convert one (or both) of operand to float to prevent floor-division:

>>> float(b - a) / n
0.14285714285714285