Re: Absolute value of signed 32-bit random integer
Arne Vajh?j wrote:
Tom Anderson wrote:
....
I would go so far as to suggest that, as with strictfp, the default
rule should be changed and the keyword should enable the old behviour,
so that overflows would trigger exceptions unless the 'intlax' or
whatever keyword applied. I'd be tempted to say that code compiled
under versions of java prior to the change should be implicitly
intlax. But by now we have a really hairy situation, so maybe not.
Changing semantics of code being recompiled with a newer Java version
is not good. It creates work for those upgrading.
The integer cases of Math.abs issue could be resolved, without upgrade
problems, by adding Math.checkedAbs defined to throw
IllegalArgumentException if the input's absolute value cannot be
represented in the input type.
There are essentially two ways of treating 2's complement arithmetic:
1. As a representation of signed integer arithmetic. That works
extremely well and efficiently as long as all inputs, intermediate
values, and results fit in the range. Generally, the type should be
chosen to be wide enough that overflow cannot happen on acceptable
inputs. If the long range is not big enough for that, go to BigInteger.
Rather than changing the behavior of the current Java primitives, I
would like a range limited integer type with arithmetic operators. If I
believe all values of a variable should be in the range -10 through +10,
I would like an exception if I try to assign 11 to it. There is nothing
special about powers of two for this purpose. Of course, the compiler
and JVM would be free to use the information about the range in
selecting a representation.
2. As 2's complement binary. In this case, the programmer is aware of
the edge cases, and knows what to expect. Changing the rules could break
code in this class.
For example, see the java.util.Random implementation of nextInt(n). It
contains the expression (bits - val + (n-1) < 0). bits is in the range
[0, 2^31). val is in the range [0,bits], so bits-val is non-negative. n
is greater than zero, so n-1 is also non-negative. In signed integer
arithmetic, the expression is always false. In 32 bit 2's complement
arithmetic, it can be true.
The original problem with Random was that the parameterless nextInt()
method returns a value that is just as likely to be close to
Integer.MAX_VALUE or Integer.MIN_VALUE as to be close to zero.
Arithmetic on its result should either be done in a wider type, such as
long or BigInteger, or treated as 2's complement binary, not general
integer arithmetic.
Patricia