Why can't math deal with ints? (floor / ceiling too)

I know that in Java (and possibly in other languages), Math.pow is defined in doubles and returns double. I am wondering why on earth, people who wrote Java also did not write the int-return pow (int, int) method, which this programmer-mathematician-beginner programmer seems to be like a forehead-slap (although, obviously, it’s easy to fix) an omission . I can’t help but think that there is some kind of behind-the-scenes reason based on the intricacies of CS, which I simply don’t know, because otherwise ... yes?

On a similar topic, ceil and floor by definition return integers, so why don't they return ints?

Thanks to everyone for helping me figure this out. This is completely insignificant, but I have been looking for me for many years.

+4
source share
5 answers

java.lang.Math is just a port of what the C-math library does.

For C, I think it comes down to the fact that the processor has special instructions for executing Math.pow for floating point numbers (but not for integers).

Of course, the language could add an implementation int. In fact, BigInteger has one. This also makes sense because it powtends to lead to large numbers.

ceil and floor by definition return integers since they do not return ints

int. , double, , int, floor .

+4

, 2 31 -1, , 2 64 - 1. , .

, ~ 10 -308 ~ 10 308 53 . (, ), , .

ceil floor , ints?

, , - . , , , , -, . , , , .

+1

int double , pow double , int.

0

pow() pow() . C, , , . , 1 ( ), . O(log(p)) , - :

// p is a positive integer power set somewhere above, n is the number to raise to power p
int result = 1;
while( p != 0){
    if (p & 1){ 
        result *= n;
    }
    n = n*n; 
    p = p >> 1;
}
0

Math.pow() (JNI ). , . Java , ?

, :

(int) Math.floor(d) == (int) d;   // d > 0
(int) Math.ceil(d) == -(int)(-d); // d < 0

( Integer.MAX_VALUE Integer.MIN_VALUE).

Java

(int) Math.pow(a,b)

Math.pow NaN Infinity .

-1

All Articles