1

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.

1
  • 5
    The / operator has changed meaning in 3.x - it now always returns a float, before it would return an int if both operands were ints. Specifically, this is causing your deltax to be zero. Apply float() to either of the operands of that division to fix this. Commented Jun 7, 2019 at 19:31

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I see. Those "small" difference where unknown to me. The script now runs perfectly after doing as you said. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.