Search code examples
javapowfloorceil

Why is math.pow not natively able to deal with ints? (floor/ceil, too)


I know that in Java (and probably other languages), Math.pow is defined on doubles and returns a double. I'm wondering why on earth the folks who wrote Java didn't also write an int-returning pow(int, int) method, which seems to this mathematician-turned-novice-programmer like a forehead-slapping (though obviously easily fixable) omission. I can't help but think that there's some behind-the-scenes reason based on the intricacies of CS that I just don't know, because otherwise... huh?

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

Thanks to all for helping me understand this. It's totally minor, but has been bugging me for years.


Solution

  • 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 CPU have special instructions to do Math.pow for floating point numbers (but not for integers).

    Of course, the language could still add an int implementation. BigInteger has one, in fact. It makes sense there, too, because pow tends to result in rather big numbers.

    ceil and floor by definition return integers, so how come they don't return ints

    Floating point numbers can represent integers outside of the range of int. So if you take a double argument that is too big to fit into an int, there is no good way for floor to deal with it.