473,657 Members | 2,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding during division

Hello,

Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?
Secondly, is there anything that I can rely when right shifting a
negative int32_t. Given that int32_t is guaranteed to be stored in
two's complement format, can it be assumed that right shifting by N is
the same as division by 2^N with rounding towards -inf? e.g:

printf("%d", 3>>1); // 1
printf("%d", 1>>1); // 0
printf("%d", -1>>1); // -1
printf("%d", -3>>1); // -3

If bitwise operations have undefined behaviour on negative intN_t types,
what was the point in specifying that they must be in two's complement
format?

Regards,

Chris
Sep 12 '07 #1
6 10805
On Wed, 12 Sep 2007 13:39:26 +0100, Christopher Key wrote:
Hello,

Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?
Yes.
Secondly, is there anything that I can rely when right shifting a
negative int32_t. Given that int32_t is guaranteed to be stored in
two's complement format, can it be assumed that right shifting by N is
the same as division by 2^N with rounding towards -inf? e.g:

printf("%d", 3>>1); // 1
printf("%d", 1>>1); // 0
printf("%d", -1>>1); // -1
printf("%d", -3>>1); // -3

If bitwise operations have undefined behaviour on negative intN_t types,
what was the point in specifying that they must be in two's complement
format?
Bitwise shifts on signed integers are implementation defined. For
example the sign bit may be treated differently.
--
Army1987 (Replace "NOSPAM" with "email")
If you're sending e-mail from a Windows machine, turn off Microsoft's
stupid “Smart Quotes” feature. This is so you'll avoid sprinkling garbage
characters through your mail. -- Eric S. Raymond and Rick Moen

Sep 12 '07 #2
Army1987 wrote:
On Wed, 12 Sep 2007 13:39:26 +0100, Christopher Key wrote:
>Hello,

Could anyone tell me what the various C standards say on the
subject of rounding during signed integer division. On my
system, it always rounds towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?
Yes.
No. That is only true for C99.
There are still many C89-C95 implementations and they were
allowed to make their own decision:

| If either operand is negative, whether the
| result of the / operator is the largest integer less than the
| algebraic quotient or the smallest integer greater than the
| algebraic quotient is implementation-defined, as is the sign
| of the result of the % operator.

Ralf
Sep 12 '07 #3
On Wed, 12 Sep 2007 15:13:04 +0200, in comp.lang.c , Army1987
<ar******@NOSPA M.itwrote:
>On Wed, 12 Sep 2007 13:39:26 +0100, Christopher Key wrote:
>Hello,

Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:

printf("%d", 3/2); // 1
printf("%d", 1/2); // 0
printf("%d", -1/2); // 0
printf("%d", -3/2); // -1

Can I rely on this always being the case?
Yes.
No. For the positive cases, you can rely on it. For the negative
cases, compilers may round up or down, depending on which version of
the C standard they comply to.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Sep 12 '07 #4
On Sep 13, 1:13 am, Army1987 <army1...@NOSPA M.itwrote:
On Wed, 12 Sep 2007 13:39:26 +0100, Christopher Key wrote:
Could anyone tell me what the various C standards say on the subject of
rounding during signed integer division. On my system, it always rounds
towards 0:
Can I rely on this always being the case?

Yes.
In fact it is implementation-defined in C90, whether it
rounds up or down for negative intergers.
Bitwise shifts on signed integers are implementation defined.
No. There are four cases:
1. Right-shift of non-negative value: well-defined
2. Right-shift of negative value: implementation-defined
3. Left-shift of negative value: undefined
4. Left-shift of non-negative value: undefined if the
shift would cause an overflow, otherwise well-defined

Sep 13 '07 #5
On Sep 17, 4:18 am, Christopher Key <cj...@cam.ac.u kwrote:
Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.
typedef int assertion_dummy _array[(-value >shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.

Sep 17 '07 #6
Justin Spahr-Summers wrote:
On Sep 17, 4:18 am, Christopher Key <cj...@cam.ac.u kwrote:
>Is there any clean, portable way of acheiving signed integer division by
a power of 2 with rounding towards -inf (under C99). gcc guarantees
that right-shifts on a signed integer will always give this behaviour,
and I'm guessing that pretty much any code compiled for a target with an
ASR instruction will do the same, but I really don't want the code to
silently break for compilers that don't.

The options seem to be:

1) Discover how right shift of negative values is implemented using
preprocessor macros and issue an error at compile time if required. I
don't think this is possible, although a useful extension to the C
standard might be to force the provision of macros that allow code to
determine how implementation defined behaviour has been implemented.

typedef int assertion_dummy _array[(-value >shiftbits == othervalue)
* 2 - 1];

If the condition given in the parentheses evaluates to false (0), then
the array typedef will have a negative size, which should issue a
compiler diagnostic.
I'll give that a go. It'd be interesting to know how many compilers
warn correctly in all cases, even when cross compiling for a platform
with different shift instructions available to those on the host.

Regards,

Chris
Sep 18 '07 #7

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

Similar topics

0
1522
by: Ron Adam | last post by:
With all the discussion about numbers here and particularly in regards to prePEP concerning decimal data types got me wondering about how numbers are handled when it comes to rounding. And if that can be improved. My thought/question is, is it possible to have a numeric varable where weather or not it's value has been rounded, and which way, is persistent? For example using 2 bits to represent this you would have something
3
9398
by: Dalan | last post by:
Is there any code available to address currency rounding problems in Access 97? Apparently, selecting currency type table fields does not resolve the problem. For instance, in my form I have a price of item field (say $49.95), and a percentage discount field (say 10% = $5.00), and calculated net cost field of the two. Access seemingly doesn't understand banker's rules as the resulting total is $44.96. Could this be a bug? Why does it...
20
15876
by: Daisy | last post by:
Something simple, I'm sure. My code: System.Windows.Forms.MessageBox.Show(((Int32)Math.Ceiling(1966 / 100)).ToString()); I'm expecting 20, but getting 19. What am I doing wrong? Thanks --
3
1930
by: John C Kirk | last post by:
I've come across an odd situation, where doing a floating point division produces different results for the same numbers. Basically, there are 4 ways to run this application: A) Debug build, inside the IDE B) Debug build, outside the IDE (e.g. launched from Explorer) C) Release build, inside the IDE D) Release build, outside the IDE Using methods A-C produces one result, and using method D produces a
9
6635
by: Joe Attardi | last post by:
Hi all, Math is not my strongest area so forgive me if I use some of the wrong terminology. It seems that scientific notation is immune to rounding errors. For example: (4.98 * 100) + 5.51 // returns 503.51000000000005, rounding error! 4.98e2 + 5.51 // returns 503.51, correct!
10
3175
by: Mike S | last post by:
Does anyone know the logic behind why in VB.NET the result of a floating-point division ('/') is -rounded- on being converted to an integer type, such as with statements like Dim x As Integer = 2/3 'after assignment, x is 1, whereas a sane person would say it should be 0 Does Microsoft have a reason for this design decision? I understand that this type of rounding can reduce the overall error in long computation chains by reducing the...
94
11457
by: krypto.wizard | last post by:
Last month I appeared for an interview with EA sports and they asked me this question. How would you divide a number by 7 without using division operator ? I did by doing a subtraction and keeping a counter that kept a tab on how many times I subtracted. Later, the EA sport guy told me that of course there are can be better technique by using bit operator.
206
13224
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
20
4987
by: jacob navia | last post by:
Hi "How can I round a number to x decimal places" ? This question keeps appearing. I would propose the following solution #include <float.h> #include <math.h>
0
8303
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8821
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8723
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7316
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
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
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.