Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

divide by zero encountered in double_scalars for derivative calculations

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
like image 909
Dhaval Gadariya Avatar asked Dec 17 '15 04:12

Dhaval Gadariya


2 Answers

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
like image 79
falsetru Avatar answered Sep 20 '22 05:09

falsetru


you can also import below future to avoid floor division.

from __future__ import division
like image 23
elulue Avatar answered Sep 24 '22 05:09

elulue