473,569 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

negative integer division

integer division and modulo gives different results in c and python,
when negative numbers
are involved. take gdb as a widely available c interpreter
print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c).
from an algebraic point of view, python seems right, but I thought
python conformity to the underlying c compiler was a strong commitment,
obviously not here, and I found no explanation whatsoever in python doc.
no actual programming challenge for me here, I just had this bug, after
confidently translating from python to c.

Jul 18 '05 #1
19 5142

Imbaud> integer division and modulo gives different results in c and
Imbaud> python, when negative numbers are involved.

http://www.python.org/doc/faq/progra...22-10-return-3

Skip
Jul 18 '05 #2
Imbaud Pierre wrote:
integer division and modulo gives different results in c and python,
when negative numbers
are involved. take gdb as a widely available c interpreter
print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c).
from an algebraic point of view, python seems right, but I thought
python conformity to the underlying c compiler was a strong commitment,
obviously not here, and I found no explanation whatsoever in python doc.
no actual programming challenge for me here, I just had this bug, after
confidently translating from python to c.


I don't think there's much *commitment* to follow the behaviour of your
C compiler. It's more of a default stance when the issues get too
complicated for Python to implement itself. Thus, much of the floating
point behaviour defaults to the behaviour of your platform because
floating point math is hard and getting consistent behaviour on lots of
platforms is really hard.

Integers are a piece of cake, relatively speaking, and I think that it's
worth fixing up a few warts from the C behaviour.

As for documentation, see
http://www.python.org/doc/current/lib/typesnumeric.html

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Jul 18 '05 #3
Imbaud Pierre wrote:
integer division and modulo gives different results in c and python,
when negative numbers
are involved. take gdb as a widely available c interpreter
print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c).
from an algebraic point of view, python seems right, but I thought
python conformity to the underlying c compiler was a strong commitment,
obviously not here, and I found no explanation whatsoever in python doc.
no actual programming challenge for me here, I just had this bug, after
confidently translating from python to c.

If you read the C standard, you can see that the C compiler is free to
make -1 / 3 either -1 or 0 (but it must describe what it does). The
decision is usually to do whatever the underlying CPU does. The
rationale is that often you will be dividing positive by positive,
and you don't want the compiler sprinkling around a lot of test code.

While the difference in compiled C is a substantial time penalty
(DIVIDE vs. DIVIDE; COMPARE; JUMPGE), in Python the trade-off is
adding two instructions to many (50? 100?). Python doesn't really
mind paying for a few extra instructions to get the canonical value,
and the guarantee simplifies the user's code.

--Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #4
Imbaud Pierre <pi***********@ wanadoo.fr> writes:
integer division and modulo gives different results in c and python,
when negative numbers
are involved. take gdb as a widely available c interpreter
print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c).
from an algebraic point of view, python seems right, but I thought
python conformity to the underlying c compiler was a strong commitment,


AIUI the C standard is silent on the issue, and hence the C behavior is
implementation-dependent. Anyway back in 2000 I found and fixed a
Y2K-related problem in an open-source C program (xvtdl) which was down
to precisely this misbehavior. While diagnosing the problem I
implemented the algorithm in Python for test purposes, and was led
astray for a while by the fact that it *didn't* fail!

A: 42

Q: What multiple of 7 did I add to the critical expression in the Zeller
algorithm so it would remain nonnegative for the next few centuries?

--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
People who write obscurely are either unskilled in writing
or up to mischief. - Sir Peter Medawar
Jul 18 '05 #5
Python does it right. C is allowed to do it anyway it likes, which was
a stupifyingly horrible decision, IMHO.

Way back when, there was a language named Pascal. I lobbied the Pascal
standards committee to define the modulus operator correctly, which they
eventually did. To my astonishment, they proceded to define the
division operator backwards to the modulus operator, so that division
and mod did not play together correctly. Duh.
Jul 18 '05 #6
Mark Jackson wrote:
Imbaud Pierre <pi***********@ wanadoo.fr> writes:
integer division and modulo gives different results in c and python, when negative numbers
are involved. take gdb as a widely available c interpreter
print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c). from an algebraic point of view, python seems right, but I thought
python conformity to the underlying c compiler was a strong
commitment,
AIUI the C standard is silent on the issue, and hence the C behavior is implementation-dependent.


The *original* C standard is silent on the issue, but the current
standard requires the wrong behavior.

Jul 18 '05 #7
Jive Dadson <jd*****@yahoo. com> writes:
Python does it right. C is allowed to do it anyway it likes, which was
a stupifyingly horrible decision, IMHO.


C only does it wrong if you think that C is a high level language. It
isn't - it's a portable assembler. As such, low level things (like
this, or what happens on integer overflow, or ...) are left up to the
implementation, so it can do what's most natural for the underlying
hardware. This means that when you don't care - which I'd argue is
most of the time - you get the fastest thing the machine will do. When
you do care, you have to take care of it yourself. Of course, if you
care, you probably shouldn't be writing in assembler, you should
probably be writing in a high level language - which will make sure
the low level things get done right, irregardless of what the
underlying machine does.

Now, I'll agree with you if you want to argue that some machines do
negative integer division in stupifyingly horrible ways.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #8


Mike Meyer wrote:

Jive Dadson <jd*****@yahoo. com> writes:
Python does it right. C is allowed to do it anyway it likes, which was
a stupifyingly horrible decision, IMHO.
C only does it wrong if you think that C is a high level language.


I didn't say it does it wrong. I said it does it anyway it likes --
maybe right, maybe wrong. There *is* a right way, IMHO. Python does it
that way.
[C] isn't - it's a portable assembler.
I've heard that many times, but it makes no sense to me. By definition,
the syntax of an assembly language closely resembles the format of
individual hardware instructions for a particular processor. An
assembler assembles individual hardware instructions. Back in the day,
Unix (written largely in C) and Steve Johnson's pcc (the *portable* C
compiler) together constituted a big leap forward. Implementing Unix on
new processors was infinitely easier than porting OS's written in
assembly language. So I disagree on two counts: C code is not entirely
portable, (for example, division and mod may not work the same on two
different machines), and a C compiler is most certainly not an
assembler.

Now, I'll agree with you if you want to argue that some machines do
negative integer division in stupifyingly horrible ways.


That's why I think it was a stupifyingly horrible decision.
Understandable, but in the end an s.h.d. nonetheless. It would have
been okay to define / and % correctly, in the mathematical sense, but
also provide functions quick_div() and quick_mod() that were guaranteed
to work correctly only when both arguments were positive. The way they
did it is just too error prone, akin to early optimization. It's bitten
me before, when I was called on to port code (which I did not write)
from one machine to another. Having standard operators with
under-defined behavior is just inviting trouble: long debugging
sessions, or worse, unexplained failures in the field. Of course you
and I would avoid all the pitfalls at the start. :-)

.... and now back to your regularly scheduled Python newsgroup.
Jul 18 '05 #9
On 2005-02-09, Jive Dadson <jd*****@yahoo. com> wrote:
[C] isn't - it's a portable assembler.


I've heard that many times, but it makes no sense to me.


I think the point is that C is a low-level, hardware twiddling
language to be used by people writing things like kernel code --
something that was always done in assembler before C came
along.
Now, I'll agree with you if you want to argue that some
machines do negative integer division in stupifyingly horrible
ways.


That's why I think it was a stupifyingly horrible decision.


For a language meant to write user-space applications where one
probably cares what happens when a division results in a
negative integer, it is a horrible decision. For a "portable
assembler" used to write device drivers it makes sense. People
writing that sort of code presumably know how their hardware
behaves, don't expect that everything write is portable, and
just don't do division with negative numbers. When they do
division, it's with postive numbers and they don't want to
waste the extra clock cycles to do it in a way that's
machine-independant for negative numbers.

The fact that C ended up in the rather inappropriate role of
a user-land application language is different problem.

--
Grant Edwards grante Yow! ... I think I'd
at better go back to my
visi.com DESK and toy with a few
commonMISAPPREH ENSIONS...
Jul 18 '05 #10

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

Similar topics

7
2637
by: Matthew Wilson | last post by:
Hi- I just discovered this: >>> -1 // 12 -1 >>> 1 // 12 0 >>>
2
1832
by: Michael Cornelius | last post by:
As an old C programmer, I'm surprised by some results I'm getting with integer division. For example: >>> -1/1000 -1 >>> -9/2 -5 I expect the results of these expressions to be 0 and -4, respectively.
24
19309
by: Teis Draiby | last post by:
In .NET, can I be sure that the result of a division between two integers always is truncated rather that rounded to nearest? Example: 99 / 50 = 1 regards, Teis
2
591
by: Darius Fatakia | last post by:
hi, i'm new to MS Visual Studio and C++ but not to C programming in general. i'm trying to divide two integers and get their actual quotient (eg 5/3 = 1.666667 etc). i thought i had type cast correctly, but please let me know, because it appears to be rounding off. my code follows. Thanks! void DrawLine(GLint x1, GLint y1, GLint x2, GLint...
15
35466
by: jaks.maths | last post by:
How to convert negative integer to hexadecimal or octal number? Ex: -568 What is the equivalent hexadecimal and octal number??
9
43537
by: PengYu.UT | last post by:
Hi, The usually integer division will round the result to the biggest integet smaller than the float version division.For example, 10/3 = 3. I'm wondering if there is any easy way to round it to 4 for this case? Thanks, Peng
15
3367
by: Ivan Novick | last post by:
Hi, Is it possible to have negative integer literal or only positive? As far as I understand, the code below would be a positive integer literal and the unary negative operator. x = -3.2; Thanks,
1
1861
by: Marge | last post by:
Create a java program that performs integer division. The program will ask the user for two integer numbers and will divide the dividend by the divisor.It will then output the results(quotient) and the remainder of the division. *Proof Test Case: Dividing two negative numbers Dividing two positive numbers
0
7704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7931
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7684
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7985
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3666
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1230
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
959
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.