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.

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 1
    is `x % n == 0` not applicable here? – Stephen Rauch Jan 29 '17 at 06: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? – Lin Ma Jan 29 '17 at 06:19
  • Hi Moinuddin, I clarified my question. – Lin Ma Jan 29 '17 at 06:21
  • 1
    @LinMa as floats are not accurate enough for this task, I would recommend you to use [fractions](https://docs.python.org/2/library/fractions.html). `1%0.2` -> `0.199..` and `1%Fraction(1,5)` -> `Fraction(0,1)` – ovs Jan 29 '17 at 07:12
  • @ovs, thanks! Will try, do you think the solution posted by abccd will work? That solution seems much simpler than fraction? – Lin Ma Jan 31 '17 at 03:00
  • 1
    It will work for his example, but only for floats like '.125, .5, .75' – ovs Jan 31 '17 at 06:29
  • 1
    It won't work for floats like `0.1` and `0.2` as they can't be represented in binary – ovs Jan 31 '17 at 06:34
  • Thanks @ovs, but in your solution, why you check only for `Fraction(0,1)`, I think as long as numerator is `0`, it is ok, why do you care denominator must be `1`? – Lin Ma Jan 31 '17 at 07:36
  • `Fraction(0, 1)` is what was returned. You can just check by `==0` – ovs Jan 31 '17 at 09:35

2 Answers2

1

Try

if x % n == 0 :

hope this helps !

Jay Parikh
  • 2,419
  • 17
  • 13
  • 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? – Lin Ma Jan 29 '17 at 06:19
1

Here:

x = 25
y = 2.5 # Or something
if not x % y: # Works with float too
    print 'can divide'
else:
    print 'cannot divide'
Taku
  • 31,927
  • 11
  • 74
  • 85
  • 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? – Lin Ma Jan 29 '17 at 06:19
  • 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)? – Lin Ma Jan 31 '17 at 02:59