0

Using Python 2.7 and -1/2 will be result in -1, since -1 is floor of -0.5. But I want to get result of 0, which is 1/2 (result in 0), then negative 1/2 (final result still 0) Wondering if there is an elegant way to do this?

My current solution is using abs and check their sign first, which seems not very elegant, wondering if anyone have more elegant solutions?

Source code in Python 2.7,

a = -1
b = 2
print a/b # output -1
# prefer -(1/2) = 0

r = abs(a)/abs(b)
if (a > 0 and b < 0) or (a < 0 and b > 0):
    r = -r
print r
Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 1
    This answer is elegant because you do not really on floating point arithmetic or sign functions http://stackoverflow.com/questions/1986152/why-doesnt-python-have-a-sign-function – Elmex80s Feb 23 '17 at 02:19
  • 1
    @Elmex80s, thanks. For "this answer", which answer do you mean? – Lin Ma Feb 23 '17 at 23:28

3 Answers3

1

Do the division, then do it again your way if it came out negative.

r = a / b
r = -(abs(a) / abs(b)) if r < 0 else r
kindall
  • 178,883
  • 35
  • 278
  • 309
1

First check the signs, then divide:

r = a/b if ((a >= 0) ^ (b < 0)) else -a/b
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Thanks DYZ, vote up and could you explain a bit more what is your purpose of `(a >= 0) ^ (b < 0)`? – Lin Ma Feb 23 '17 at 05:19
  • 1
    This expression is `True` if and only if both `a` and `b` have the same sign. – DYZ Feb 23 '17 at 05:20
  • Thanks DYZ, `^` is XOR, it should operate on bits, but `(a>=0)` or `(b<0)` returns True or False, how do you do XOR on True and False? – Lin Ma Feb 23 '17 at 23:28
  • `True` is 1, and `False` is 0. – DYZ Feb 23 '17 at 23:32
  • @DYZ You may wanna fix your expression, this wouldn't work when a < 0 and b > 0, for ex: a = -1 and b = 2 – AnukuL Sep 18 '21 at 11:15
  • @AnukuL wrong. It works correctly for a=-1 and b=2. Have you tried? – DYZ Sep 18 '21 at 17:31
  • @DYZ am I missing something? a, b = -1, 2 r = a/b if ((a >= 0) ^ (b < 0)) else -a/b print(r) 0.5 Shouldn't the output be -0.5 ? – AnukuL Sep 19 '21 at 13:56
  • @AnukuL Yes, you are missing something: you use the wrong Python (3.x instead of 2.7). – DYZ Sep 19 '21 at 16:01
-1

What about this

int(a / float(b))

The int function does the trick:

>>> int(-0.999)
0
>>> int(0.999) 
0

I see that is also one of the answers to this question In Python, what is a good way to round towards zero in integer division?

Community
  • 1
  • 1
Elmex80s
  • 3,428
  • 1
  • 15
  • 23