File: MathAbsoluteNegative.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (32 lines) | stat: -rw-r--r-- 1,067 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[`Math.abs`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-long-)
returns a negative number when called with the largest negative number.

Example:

```java
int veryNegative = Math.abs(Integer.MIN_VALUE);
long veryNegativeLong = Math.abs(Long.MIN_VALUE);
```

When trying to generate positive random numbers or fingerprints by using
`Math.abs` around a random positive-or-negative integer (or long), there will a
rare edge case where the returned value will be negative.

This is because there is no positive integer with the same magnitude as
`Integer.MIN_VALUE`, which is equal to `-Integer.MAX_VALUE - 1`. Floating point
numbers don't suffer from this problem, as the sign is stored in a separate bit.

Instead, one should use random number generation functions that are guaranteed
to generate positive numbers:

```java
Random r = new Random();
int positiveNumber = r.nextInt(Integer.MAX_VALUE);
```

or map negative numbers onto the non-negative range:

```java
long lng = r.nextLong();
lng = (lng == Long.MIN_VALUE) ? 0 : Math.abs(lng);
```