Division by zero occurs in double_scalars for derived calculations

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

Here is 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
+4
source share
2 answers

In Python 2.7, integer division does floor:

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

=> dxbecomes 0.0=> Inside the body of the cycle for, it is used as a divisor. (0 2 = 0)

( ) float, :

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

future, .

from __future__ import division
0

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


All Articles