By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,172 Members | 727 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,172 IT Pros & Developers. It's quick & easy.

Strange issue with normal operations

P: 16
Hello, I was writing a very simple code and I noticed something was failing. I detected the problematic part but I CANNOT find wheres the error.

The code is:

Expand|Select|Wrap|Line Numbers
  1. def pri(max):
  2.     for m in range(1,max):
  3.         num=(m+1)/m
  4.         if num==1: print 'ERROR'
  5.         else: print 'OK'
The problem is that it prints:
Expand|Select|Wrap|Line Numbers
  1. ERROR
  2. ERROR
  3. ERROR
  4. ERROR
  5. ERROR
  6. ERROR
  7. ERROR
  8. #...
Is there any syntax problem (I dont work with python since a long time)? Or a logical problem? Or my microprocessor just went crazy?

I hope you can help me.

Thank you very much.
Mar 7 '11 #1
Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
To see what is taking place, take a look at the following interaction with the interpreter:
Expand|Select|Wrap|Line Numbers
  1. >>> (1+1)/1
  2. 2
  3. >>> (2+1)/2
  4. 1
  5. >>> (3+1)/3
  6. 1
  7. >>> (4+1)/4
  8. 1
  9. >>> 
Integer division returns the floor.
Mar 7 '11 #2

P: 16
But which would be the correct form?
Because neither
Expand|Select|Wrap|Line Numbers
  1. num=(m+1)/float(m)
nor
Expand|Select|Wrap|Line Numbers
  1. num=(m+1)/(m*1.0)
are correct.
Mar 7 '11 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Either would return a float. What would be correct?
Mar 7 '11 #4

P: 16
But the problem is that they return 1, not a floating point.
Mar 7 '11 #5

bvdet
Expert Mod 2.5K+
P: 2,851
I don't see the behavior you are describing.
Expand|Select|Wrap|Line Numbers
  1. >>> (1+1)/float(1)
  2. 2.0
  3. >>> (2+1)/float(2)
  4. 1.5
  5. >>> (3+1)/float(3)
  6. 1.3333333333333333
  7. >>> (1+1.)/1
  8. 2.0
  9. >>> (2+1.)/2
  10. 1.5
  11. >>> 
Mar 7 '11 #6

Post your reply

Sign in to post your reply or Sign up for a free account.