Do you like bounded integrals?

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 30 07:58:16 PDT 2016


On Tue, 30 Aug 2016 13:24:04 +0000, tsbockman wrote:
> On Tuesday, 30 August 2016 at 03:37:06 UTC, Chris Wright wrote:
>> On Mon, 29 Aug 2016 18:20:05 +0000, tsbockman wrote:
>>> They should. Generally speaking, if that doesn't produce reasonable
>>> bounds (leaving aside rounding errors) at the end of the computation,
>>> it means that the logic of the computation itself is wrong.
>>
>> The ranges expand very fast. Addition and subtraction double the range,
>> multiplication squares it, exponentiation is n^^n.
>> Larger bounds are usually not useful bounds.
> 
> Ranges don't always grow. Some operations will also cause them to
> shrink, if they're really being tracked correctly:

We can only track types, not values, and that strongly hampers our 
ability to reduce ranges. We can still do it sometimes, but no operation 
always reduces ranges (and every operation sometimes extends ranges).

> bitwise AND,

It tends to extend the lower bound. For instance:

Bounded!(int, -100, 5) a = -99, b = -32;
auto c = a & b;

Here, c has type Bounded!(int, -128, 5) and value -128.

Similarly, Bounded!(int, 7, 55) & Bounded!(int, 12, 64) yields Bounded!
(int, 0, 55).

And for an odd one, Bounded!(int, 50, 55) & Bounded!(int, 60, 62) yields 
Bounded!(int, 48, 54).

So bitwise AND *sometimes* reduces the range (in sometimes hard to 
predict ways), but it also sometimes extends it.

> integer division,

You can only reduce a range with integer division if the divisor's static 
range does not include the identity. For example (assuming the range is 
open on both ends):

Bounded!(int, 0, 100) a = 1, b = 100;
auto c = b / a;

c has type Bounded!(0, 100) and value 100.

On the other hand, it can sometimes reduce the range:

Bounded!(int, 4, 8) a = 4, b = 8;
auto c = b / a;

Here, c has type Bounded!(int, 1, 2) and value 2.

And sometimes it extends the range:

Bounded!(int, -1, 1) a = -1;
Bounded!(int, 0, 128) b = 128;
auto c = a / b;

Here, c has type Bounded!(int, -128, 128) and value -128.

> and modulus all tend to do so.

Modulus can result in a range larger than its operands':

Bounded!(int, 1, 2) a = 1, b = 2;
auto c = b % a;

Here, c has type Bounded!(int, 0, 2) and value 0.


More information about the Digitalmars-d mailing list