luke
luke

Reputation: 13

Find the maximum value of a float without using Float.MAX_VALUE?

My question is similar to this one. As far as I can tell, you cannot bit shift a float in Java. If that is the case how would I got about calculating the maximum value of a float without using Float.MAX_VALUE?

Upvotes: 1

Views: 709

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Brute force. This method does not depend on knowing the structure of a float, just that 1 is in the finite float range, and that Math.nextUp(float) and Float.isFinite(float) both work. It could be made faster by first doubling until next is infinite, then using nextUp.

public strictfp class Test {
    public static void main(String[] args) {
        float max = maxFloat(1);
        System.out.println(max);
    }


    /**
     * @param f A starting point.
     * @return Largest finite float.
     */
    static float maxFloat(float f) {
        float next = Math.nextUp(f);
        while(Float.isFinite(next)) {
            f = next;
            next = Math.nextUp(f);
        }
        return f;
    }
}

Output:

3.4028235E38

Upvotes: 1

MT756
MT756

Reputation: 629

(2-2^-23)·2^127 is the maximum value for a float

float f = Float.intBitsToFloat(0x7f7fffff);
System.out.println(f);
float f1 =  0x1.fffffeP+127f;
System.out.println(f1);

both print 3.4028235E38 as in the java documentation

Or you can play around using math to get the same value

Upvotes: 1

Related Questions