0

I have run the following code snippet:

#Physics Equations

#Default_Variables
default_path = 10000
default_time = 18000
default_ini_vel = 1
default_acceleration = 1

#Variables
path = default_path
time = default_time
ini_vel = default_ini_vel
acceleration = default_acceleration

#Compute
avg_spd = path / time
velocity = (ini_vel + (acceleration * time))

#Prints
print("Average Speed = " + str(avg_spd))
print("Velocity = " + str(velocity))

I have expected the code to return a float type value for average speed containing many decimal places. The output for average speed equals 0. Why?

3
  • I have successfully run the program before. But the problem started showing up the next time I run it. Commented Aug 18, 2018 at 10:04
  • 1
    Division with / works differently in python 3 and python 2. Presumably you are using 2 now, where the / operator does integer division,i.e. rounded down to the nearest integer. In this case, zero. You can avoid this by converting your values to floats before dividing them. Commented Aug 18, 2018 at 10:12
  • Thanks, Forgot I had both python 2 and 3 with me. Used the wrong one. Commented Aug 18, 2018 at 10:28

4 Answers 4

1

As others have already observed, the most likely culprit is avg_spd = path / time. In Py2 this is integer division, and the result gets rounded down to the nearest integer. In Py3 this behaviour has changed, and returns the perhaps more intuitive floating-point result.

You can get this 'new' behaviour in Py2 as well, by importing,

from __future__ import division

Above your code.

Sign up to request clarification or add additional context in comments.

Comments

1

Division with / works differently in python 3 and python 2. Presumably you are using 2 now, where the / operator does integer division, i.e. rounded down to the nearest integer. In this case, zero. You can avoid this by converting your values to floats before dividing them:

avg_spd = float(path) / time

Comments

0

In Python2, division of two integers will always result in a rounded up integer. So, in your case the answer will be rounded up result of 10000/18000 which will be 0.

In Python3 you will get a float, which is the answer you actually want. But if you want the same answer in Python2 then just type cast your path to float and you will get the desired answer in float:

avg_speed = (float)path/time

Comments

0

Python 3 will give a float as the answer to division of two integers and Python 2 will give an int.

In your case, cast one of them to float when you do the division.

Comments

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.