0

How to do floating point computation in python ?

  for j in range(10 , 50):      
         print "(10/(j+1)) is %f " % (10/(j+1))

Why is the output all 0s ?

j must be an integer , but I need the floating result .

thanks

2 Answers 2

7

In Python2, / will truncate the quotient of two integers into an integer,

you can either do

  for j in range(10 , 50):      
      print "(10/(j+1)) is %f " % (10.0/(j+1))

or not to truncate globally, just as Python3 does

from __future__ import division

for j in range(10 , 50):      
    print "(10/(j+1)) is %f " % (10/(j+1))
Sign up to request clarification or add additional context in comments.

Comments

1

try 10.0 instead of 10. python is interpreting the 10 as an integer type and the division as a result is integer division. You could also cast 10 or (j + 1) to a double type manually but 10.0 seems the easiest to me.

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.