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
2
  • 1
    This answer is elegant because you do not really on floating point arithmetic or sign functions stackoverflow.com/questions/1986152/… Commented Feb 23, 2017 at 2:19
  • 1
    @Elmex80s, thanks. For "this answer", which answer do you mean? Commented Feb 23, 2017 at 23:28

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Or use reverse floor division..
Thanks kindall, like your method and vote up. It looks like no straightforward solution in Python?
1

First check the signs, then divide:

r = a/b if ((a >= 0) ^ (b < 0)) else -a/b

8 Comments

Thanks DYZ, vote up and could you explain a bit more what is your purpose of (a >= 0) ^ (b < 0)?
This expression is True if and only if both a and b have the same sign.
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?
True is 1, and False is 0.
@DYZ You may wanna fix your expression, this wouldn't work when a < 0 and b > 0, for ex: a = -1 and b = 2
|
-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?

2 Comments

The int function does not do the trick for e.g. int(-1/2) in Python 2.
@TigerhawkT3 You should do int(-1/float(2)) which does work in Python 2.7!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.