Fred
Fred

Reputation: 11

Python 2.7.12 does not run properly my script

Running a python script using python 2.7.12 does not give the expected answer. However, using python 3.5.2 to run it, does.

I have Ubuntu 16.04 and python 2.7.12 installed (default) and also python 3.5.2

I have run the script in another Linux machine with python 2.7.12 and the problem is the same.

I think the problem lies in the for loop used to calculate the variable (y in the script). It seems that it does not update it.

from numpy import *
from matplotlib.pyplot import *
import seaborn as sns


sns.set_style('whitegrid')

x0=0
y0=1
xf=10
n=101
deltax=(xf-x0)/(n-1)
x=linspace(x0,xf,n)
y=zeros([n])
y[0]=y0

for i in range(1,n):
    y[i] = deltax*(-y[i-1] + sin(x[i-1])) +y[i-1]

for i in range(n):
    print(x[i],y[i])

plot(x,y,'o')
show() 

Expect a plot of a sine function.

python 3.5.2 plots a sine function but python 2.7.12 plots a flat horizontal line.

Upvotes: 1

Views: 46

Answers (1)

dhke
dhke

Reputation: 15398

Your problem is here

deltax=(xf-x0)/(n-1)

The / operator differs between Python 3 and Python 2. See e.g. here and PEP238

In Python 2, / between two integers performs integer division. In Python 3 it performs floating point division. Meaning that for Python 2

deltax = (xf - x0) / (n - 1) = (10 - 0) / 100 == 0

while in Python 3

deltax = (xf - x0) / (n - 1) = (10 - 0) / 100 == 0.1

If you want floating point division in Python 2, you need to request it, e.g.

deltax = (xf - x0) / float(n - 1)

Upvotes: 3

Related Questions