2005.04.25

 

Ranged numeric types

by Karel Thönissen

In this thread, there was a discussion whether zero is a natural number or not, whether unsigned numbers are useful in programming, and whether implementation width should be incorporated in the identifier of the class. I explained why ranged numeric classes can help developing better software:

>>> First thing -- most "pure" software people would rather not have to care what the native word size is of a register on the machine they are using.  That's why we have the 'int' keyword in C -- its size changes depending on what platform you use it on.<<<

I beg to differ most strongly. If you want to develop high integrity code, you should always specify range and precision of all your numeric types. Using types with range and precision left open is not giving you portable code or even future proof code (when compilers, platforms change).

Granted, code using Int128 may not run on some machines, but the compiler will tell you up front. If the 128-bit-ness is a domain requirement, then you are lucky: you have been saved from disaster by the compiler. If the 128-bit-ness is not a domain requirement, then the question is why it was there in the first place.

If what you really want is (almost) limitless range, then use BigNums, and thus, specify that explicitly.

An even better technique in this area is by explicitly specifying the range of possible values and letting the compiler pick the best internal representation (as in the Carmen-language):

  class Age: Nat range 0...130

This range invariant provides additional semantic information that will help you catch errors and provides total freedom to the compiler to use any suitable implementation type.

There is a lot of merit in being Ada-aware (-8

>>>Actually there is no agreement on whether or not zero is a natural.<<<

In some of the math books and literature that I have access to, it is stated that there is some controversy over the question whether zero is a natural number. After having spent two sentences on the subject, *all* these books and papers continue assuming that zero is a natural.

>>>I am strongly tending towards the view that there is never a good reason to use unsigned numbers.<<<

Why is that? At Garabit we use Integers, Naturals and Cardinals all of the time, and they help us to catch errors by allowing us to express invariance constraints for the value domain. However, I must confess that we have defined our own implementations for these types, because the standard ones in Delphi are broken. other than that, subrange types in Pascal are extremely useful. In fact they are a poor man's invariants (as in DbC).