Arithmetic limitations
Expect the unexpected:
byte count = 91; // o.K.
int i = 91;
byte count2 = i; // Compile error: Incompatible types
// Required: byte Found: int
byte points = 130; // Compile error: Incompatible types
// Required: byte Found: intWhy not generally using float / double in favour of
seemingly more limited byte, short, int, long for
arithmetics?
| Code | long longValue = 1000000001L; float fValue = longValue; System.out.format(" float value: %19.0f\n", fValue * fValue); double dValue = longValue; System.out.format("double value: %19.0f\n", dValue * dValue); IO.println(" Exact value: " + longValue * longValue); |
|---|---|
| Result | float value: 999999984306749400 double value: 1000000002000000000 Exact value: 1000000002000000001 |
Figure 112.
FloatConverter | Code | // Trying to represent 0.1F: »%18.16f« prints 16 fractional // digits within a 18 character long field final int LOWER = 0b0_01111011_10011001100110011001100, UPPER = 0b0_01111011_10011001100110011001101; System.out.format("%18.16f\n", Float.intBitsToFloat(LOWER)); System.out.format("%18.16f\n", Float.intBitsToFloat(UPPER)); |
|---|---|
| Result | 0.0999999940395355 (too small) 0.1000000014901161 (too big) |
Figure 114.
FloatConverter | Code | Result |
|---|---|
int result1 = 5 / 3; IO.println("result1: " + result1); double result2 = 5 / 3; IO.println("result2: " + result2); double result3 = 5.0 / 3; IO.println("result3: " + result3); |
result1: 1 result2: 1.0 result3: 1.6666666666666667 |
See 15.17.2. Division Operator / for details
