Reputation: 35
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?
Upvotes: 0
Views: 152
Reputation: 68
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.
Upvotes: 0
Reputation: 1
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
Upvotes: 0
Reputation: 6574
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.
Upvotes: 1
Reputation: 24351
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
Upvotes: 1