0

Wondering what is the most efficient way to check if an integer can or cannot be divided by another number (could be float) in Python 2.7. Or more general, what is the most efficient way to check if an integer can be divided by n (n could be a float number) in Python 2.7.

My pain point is, if I try to get x/n, it is always an integer.

9
  • 1
    is x % n == 0 not applicable here? Commented Jan 29, 2017 at 6:09
  • @StephenRauch, maybe it is my issue not state my question very clear, I want to handle situation when n is a float number. Any thoughts? Commented Jan 29, 2017 at 6:19
  • 1
    @LinMa as floats are not accurate enough for this task, I would recommend you to use fractions. 1%0.2 -> 0.199.. and 1%Fraction(1,5) -> Fraction(0,1) Commented Jan 29, 2017 at 7:12
  • 1
    It will work for his example, but only for floats like '.125, .5, .75' Commented Jan 31, 2017 at 6:29
  • 1
    It won't work for floats like 0.1 and 0.2 as they can't be represented in binary Commented Jan 31, 2017 at 6:34

2 Answers 2

1

Try

if x % n == 0 : 

hope this helps !

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

1 Comment

Thanks Jay, maybe it is my issue not state my question very clear, I want to handle situation when n is a float number. Any thoughts?
1

Here:

x = 25 y = 2.5 # Or something if not x % y: # Works with float too print 'can divide' else: print 'cannot divide' 

2 Comments

Thanks abccd, maybe it is my issue not state my question very clear, I want to handle situation when n is a float number. Any thoughts?
Thanks, but I am not sure if your method will have issue because Python floating point calculation is not 100% accurate, suppose X can be divided by Y (Y is a float number), but Python gets a result which is a fraction other than an integer (because of Python floating calculation approximate itself)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.