Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With c++ integers, does 1 divided by 2 reliably equal 0, and 3/2 = 1, 5/2 = 2 etc.?

There are two vectors of differing, yet related sizes. The larger is (2 * RESOLUTION) + INDEX_OFFSET (e.g. 2050) and the smaller is simply RESOLUTION (e.g. 1024). I believe it safe enough to assume that uint16_t can be used to contain the vector index.

Iteration through the larger vector is performed by incrementing resultIndex by 2. During each iteration, an assignment is made to the smaller vector at the index (resultIndex - INDEX_OFFSET) / 2.

Essentially, the code relies on the assumption that, whether INDEX_OFFSET is odd or even, the above division by 2 will always round down, regardless of architecture. For example, if resultIndex is 0 or 1, then 0 is expected, if is it 2 or 3 then 1 is expected, and so on. Is this a safe assumption, within the parameters above?

N.B. I acknowledge the existence of 'Dividing integer types - Are results predictable?' but it does not seem to be an exact match.

like image 941
mosi Avatar asked Jan 11 '13 16:01

mosi


People also ask

What happens when you divide integers in C?

Integer division yields an integer result. For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division.

How do you do remainders in C?

Use the modulus operator % , it returns the remainder.

What would be the datatype of the output obtained by performing division using '/'?

The '/' operator is used to perform division operation on data values of both the data types i.e. 'float' and 'int'. The beauty of Python '/' operator is that this operator can handle decimal as well as negative values, respectively.


1 Answers

Yes; this is guaranteed by the language:

[C++11: 5.6/4]: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

In 3/2, both 3 and 2 are integral operands; the algebraic quotient of this operation is 1.5, and when you discard the fractional part .5, you get 1. This holds for your other examples and, well, all other examples.

like image 61
Lightness Races in Orbit Avatar answered Sep 21 '22 15:09

Lightness Races in Orbit