Kelsier
Kelsier

Reputation: 33

Why does decrementing Integer.MIN_VALUE by Math.pow() return the same value?

on executing :

        int p=-2147483648;
        p-=Math.pow(1,0);  
        System.out.println(p);
        p-=1;
        System.out.println(p);
Output: -2147483648
         2147483647 

So why doesn't Math.pow() overflow the number?

Upvotes: 3

Views: 98

Answers (2)

Turing85
Turing85

Reputation: 20195

We start the discussion by observing that -2147483648 == Integer.MIN_VALUE (= -(2³¹)).

The expression p -= Math.pow(1,0) has an implicit cast from double to int since Math.pow(...) returns a double. The expression with an explicit cast looks like this

p = (int) (p - Math.pow(1,0))

Ideone demo

Even more spread out, we get

double d = p - Math.pow(1,0);
p = (int) d;

Ideone demo

As we can see, d has the value -2.147483649E9 (= -2147483649.0) < Integer.MIN_VALUE.

The behaviour of the cast is governed by Java 14 JLS, §5.1.3:

5.1.3. Narrowing Primitive Conversion

...

A narrowing conversion of a floating-point number to an integral type T takes two steps:

  1. In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

    • If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.

    • Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

      • If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

      • Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

    • Otherwise, one of the following two cases must be true:

      • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

      • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

In the second step:

  1. If T is int or long, the result of the conversion is the result of the first step.

...

Upvotes: 5

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2266

Please note that Math.pow() operates with arguments of type Double and returns a double. Casting it to int will result in the expected output:

public class MyClass {
    public static void main(String args[]) {
        int p=-2147483648;
        p-=(int)Math.pow(1,0);  
        System.out.println(p);
        p-=1;
        System.out.println(p);
    }
}

The above produces the following output:

2147483647

2147483646

Upvotes: 1

Related Questions