Raising a floating position to a certain power in Java

I have a xtype variable floatthat needs to be raised to a certain power p. If there xwas double, I could use Math.pow(x, p). Is it possible to calculate x^pthat the result is also float?

+3
source share
3 answers

Evaluating powin doubleand converting to floatwill almost always produce the same results as evaluating implementation float pow. To see this, consider the exact mathematical value x p . If, using the rounding mode to the nearest to it, the values ​​are rounded to doubleand then rounded to float, the result will be the same as rounding directly to float if rounding to has doublemoved the value to the border where rounding to changes float.

24 th ( 0 th). double 53- . , double , float , 24 53 , .

[- ; .]

0:

               Bit 23 24 25-52 53 54…
Original            1  0 11…11  1 anything
Rounded to double   1  1 00…00  0 0… (53 above midpoint: rounds up, carries to higher bits)
Then to float       0  0 00…00  0 0… (24 at midpoint, 23 is odd: rounds up, carries into bit 22, not shown)
Directly to float   1  0 00…00  0 0… (24 below midpoint: rounds down)

1:

               Bit 23 24 25-52 53 54…
Original            0  1 00…00  0 anything except all zeroes
Rounded to double   0  1 00…00  0 0… (53 below midpoint: rounds down)
Then to float       0  0 00…00  0 0… (24 at midpoint, 23 is even: rounds down)
Directly to float   1  0 00…00  0 0… (24 above midpoint: rounds up)

2:

               Bit 23 24 25-52 53 54…
Original            0  1 00…00  1 0…
Rounded to double   0  1 00…00  0 0… (53 at midpoint, 52 is even: rounds down)
Then to float       0  0 00…00  0 0… (24 at midpoint, 23 is even: rounds down)
Directly to float   1  0 00…00  0 0… (24 above midpoint: rounds up)

0 , 31 , 2 31 , . 1 , , , , . 2 , , . , , 1 2 .

1 2 30.

, , a double float, , float .

, pow . , , . ( .) , . double, float .

+6

, .

public float power(final float base, final int power) {
    float result = 1;
    for( int i = 0; i < power; i++ ) {
        result *= base;
    }
    return result;
}

EDIT:

, , float , float.

:

public static void main(final String[] args) {
    System.out.println( power(Float.MAX_VALUE, 2));
}

:

Infinity

, .

EDIT:

, , double , float . Math.pow(), .

, , SO

+2

Math.pow(x, p);

float x double, . , , .

EDIT: , float, Math.pow, double float .

public float myPow(float x, float p) {
    double dblResult = Math.pow(x, p);
    float floatResult = (float)dblResult; // <-- Change to something safe. It may easily overflow. 
    return floatResult;
}
0

All Articles