473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

simple math question

Hi all. I'm just starting out with Python, so I'm a little slow right
now. :)

Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the current
way that the / operator is implemented, but why doesn't it evaluate to
-2 instead?
Feb 11 '06 #1
10 1351
Em Sáb, 2006-02-11 Ã*s 14:52 -0500, John Salerno escreveu:
Hi all. I'm just starting out with Python, so I'm a little slow right
now. :)

Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the current
way that the / operator is implemented, but why doesn't it evaluate to
-2 instead?


It has to do with floating point operations. If you evaluate 5 / -2.0 or
5.0 / -2 you will have -2.5. It gives you -3 because of rounding to
integers. Look:
round(-2.5) -3.0 round(+2.5)

3.0

This behavior is because -round(x) should be equal to round(-x).

Cya,
Felipe.

--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"

Feb 11 '06 #2
John Salerno wrote:
Hi all. I'm just starting out with Python, so I'm a little slow right
now. :)

Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the current
way that the / operator is implemented, but why doesn't it evaluate to
-2 instead?


Its an integer expression.

Try '5.0/-2' or '5/-2.0' or 'float(5)/-2' or '5/float(-2)' and compare
'5/-2' to '5/2'.

James
Feb 11 '06 #3
'/' is a floor division (1/2 == 0) unless validated by a from
__future__ import division.

So:
5/2=2.5 -> nearest lowest non-decimal number makes it 2.
5/-2=-2.5 -> nearest lowest non-decilmal number makes it -3

Feb 11 '06 #4
John Salerno <jo******@NOSPAMgmail.com> writes:
Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the
current way that the / operator is implemented, but why doesn't it
evaluate to -2 instead?


Well, -2 * -2 is 4, which is not especially better than 6. The
reason for choosing -3 instead of -2 is so that if b is positive,
then a%b is non-negative even if a is negative. That is, the
motivating case is (-5 % 2) which is done the same way as (5 % -2).

You want (b*(a/b) + a%b)==a at all times. If (-5 / 2) = -3, then you
need (-5 % 2) = -1. But if (-5 / 2) = -2, then (-5 % 2) = +1.
Since a%b is positive, you can use it as a list index, etc.
Feb 11 '06 #5

"John Salerno" <jo******@NOSPAMgmail.com> wrote in message
news:Ru********************@rcn.net...
Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?


With same sign int division, one can think of the result as either being
rounding down or rounding to zero. With mixed sign int division, rounding
to zero becomes rounding up, so the language designer has to choose being
consistent with one or the other but not both. There are pluses and
minuses either way and different language designers have made different
choices between the two.

Guido's rational was posted some years ago but I forget. You might be able
to find something in Google's c.l.p archives, or on the web in general.

Terry Jan Reedy

Feb 11 '06 #6
Rinzwind wrote:
'/' is a floor division (1/2 == 0) unless validated by a from
__future__ import division.

So:
5/2=2.5 -> nearest lowest non-decimal number makes it 2.
5/-2=-2.5 -> nearest lowest non-decilmal number makes it -3


Ah, this makes the most sense to me. -2.5 rounded down is -3. I guess I
was thinking of it more in terms of "-2 goes into 5 -3 times", which is
a little hard to wrap my mind around.
Feb 11 '06 #7
John Salerno wrote:
Hi all. I'm just starting out with Python, so I'm a little slow right
now. :)

Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the current
way that the / operator is implemented, but why doesn't it evaluate to
-2 instead?


Thanks for the help guys! It's clearer to me now, and I think I was just
conceptualizing it the wrong way in the first place.
Feb 11 '06 #8
Paul Rubin wrote:
John Salerno <jo******@NOSPAMgmail.com> writes:
Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the
current way that the / operator is implemented, but why doesn't it
evaluate to -2 instead?
Well, -2 * -2 is 4, which is not especially better than 6. The
reason for choosing -3 instead of -2 is so that if b is positive,
then a%b is non-negative even if a is negative. That is, the
motivating case is (-5 % 2) which is done the same way as (5 % -2).


As a more concrete example, consider the case of a Date class that
stores dates as the number of days since an epoch, which happens to be
a Sunday. To compute the day of the week a date falls on, you could
use:

SUNDAY, MONDAY, ..., SATURDAY = xrange(7)

class Date:
...
def weekday(self):
return self.daycount % 7
But what about the day BEFORE the epoch, represented by -1?

Case 1: Suppose that -1 // 7 == 0, as it is in C. In order to preserve
that
You want (b*(a/b) + a%b)==a at all times.
With a=-1, b=7, and a//b=0, this means (7*0 + a%b)==-1, which requires
that -1 % 7 == -1. This doesn't correspond to any of the weekday
constants, which means you'd have to rewrite your weekday() method if
you wanted to handle negative dates.

Case 2: Suppose that -1 // 7 = -1.

Then (7*(-1) + -1%7)==-1, which means -1%7 happens to be 6. This says
that the day before the epoch is a Saturday, which is exactly what you
want.
Since a%b is positive, you can use it as a list index, etc.


This isn't the best explanation, because negative list indices *are*
allowed.

Feb 11 '06 #9
On Sat, 11 Feb 2006 16:43:33 -0500 in comp.lang.python, John Salerno
<jo******@NOSPAMgmail.com> wrote:
John Salerno wrote:
Hi all. I'm just starting out with Python, so I'm a little slow right
now. :)

Can someone explain to me why the expression 5 / -2 evaluates to -3,
especially considering that -2 * -3 evaluates to 6?

I'm sure it has something to do with the negative number and the current
way that the / operator is implemented, but why doesn't it evaluate to
-2 instead?


Thanks for the help guys! It's clearer to me now, and I think I was just
conceptualizing it the wrong way in the first place.


Probably not the "wrong" way, just a different way, especially if you
write C code.

The C standard defines integer division as (something like) "the
integer part of the result, throwing away the fraction," which would
get you the value you expect.

This also means the sign of the result of the C % operator matches the
sign of the numerator. In Python, the sign matches the sign of the
denominator.

You could also describe the C scheme as "truncating towards zero."
Python (and my HP calculator) "truncates toward negative infinity." I
suppose a third way to do it would be to "truncate towards positive
infinity," but I don't know of any concrete examples of this. 'Twould
seem counter-intuitive in any case...

Regards,
-=Dave

--
Change is inevitable, progress is not.
Feb 13 '06 #10
Dave Hansen wrote:
Probably not the "wrong" way, just a different way, especially if you
write C code.


Oh, how poorly you know me! ;) I started learning C# a year ago, just
for fun, but that's about all I know (aside from HTML and CSS). I did
have a high school class in C++ a long, long time ago though.

Anyway, Python is my next venture, again just for fun. I guess my
problem was like you said, I was used to truncating toward zero, not
toward negative infinity. Knowing that that's how Python works fully
explains my problem now.
Feb 13 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Rob | last post by:
He , I need to generate some random numbers, right now I am using: Random pk = new Random(); int a = pk.nextInt(540); and wondering if there is any other methods in java to generate random...
20
by: drs | last post by:
Hi, I am trying to find all lists of length x with elements a, b, and c. To this end, I have created the class below, but it is not quite working and I am having trouble figuring out what to...
2
by: Senraba | last post by:
I would like to have a 600 X 400 window open with search results from CPanel's Entropy Search form. I have the following in the <HEAD> tag: <script language="javascript"...
2
by: Webdiyer | last post by:
Hi, We all know that the return value of Math.Log(8,2) is 3,but how about (int)Math.Log(8,2)? On my machine,the return value of (int)Math.Log(8,2) is strange enough! it's not 3 but 2 ! I've...
1
by: Phillip Vong | last post by:
Newbie here trying to learn. Using VS2005 / learning in VB.NET for an ASPX page. Sorry for this simple question. I have a Gridview1 with 2 columns. I added a 3rd column and all I want to do...
1
by: macklin01 | last post by:
Hi, everybody. I'm trying to do some last cleaning up on the following php page I wrote: http://www.math.uci.edu/~pmacklin/Publications.php This URL parses an XML file of publications: ...
0
by: sean | last post by:
I'm trying to create a "rubber band" rectangle effect on my form. Private Sub HighlightSectionOfTrack(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles...
5
by: gray_slp | last post by:
I am designing a web survey using surveymonkey.com and discovered I could use javascript to modify their standard question formats much the same as can be done in myspace. I used this feature to...
22
by: giordan | last post by:
Hi all! I've wrote this code: <script type="text/javascript"> var largImg; var altImg; var txtTop = '<b>Ottima scelta!</b> Ora compila il form e premi "Ricevi banner". Il...
17
by: Lenni | last post by:
Hi, I'm currently writing a web application for bicycle wheel builders that calculate the spoke length for all sorts of variations of hubs and rims. I have translated the formula from an...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.