tags:

views:

356

answers:

5

What does the following expression return in Java?

Math.max(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);

I saw this question in a website and the answer is Double.POSITIVE_INFINITY. I'm not sure about this answer as how can we compare 2 infinities? Can someone clarify this? Thanks.

+2  A: 

Certainly you can compare infinities. Unless you get into transfinite numbering systems where there are varying degrees of infinity, infinity means just what it says, a number without limit.

The maximum/sum/product/average of two numbers without limit is one number without limit.

paxdiablo
A: 

The question of whether, mathematically speaking, you can compare infinities is best left to the more mathematically literate here. But I think that in the case of Float.POSITIVE_INFINITY vs Double.POSITIVE_INFINITY it's simply the case that Double is bigger than Float and the POSITIVE_INFINITY constants are simply the maximum possible value for each data type.

"simply the maximum possible value for each data type." not so. IEEE754 floating point numbers have reserved values that represent positive and negative infinities (and Not a Number (NaN), rather than the largest possible value a la Double.MAX_VALUE.
Aaron Maenpaa
This simply is not true. Read the IEEE754 spec.
Daniel Cassidy
+19  A: 

Float.POSITIVE_INFINITY returns float and Double.POSITIVE_INFINITY returns double.

There is no method called Math.max(float, double). only Math.max(float, float) and Math.max(double, double)

Therefore when the method is called Math.max(float, double), it converts the float argument to double and so the Math.max(double, double) is called so Double.POSITIVE_INFINITY is returned.

Java does not convert from double to float since it may lead to precision problem.

Shree
this is an example of coercion polymorphism. Isn't it?
Shree
A: 

I think you will find that all operations using the special values defined for double and float types is defined in the IEEE floating point spec. Most programming languages and nearly all CPUs follow that standard.

rmeador
+2  A: 

Read the IEEE 754 spec.U can understand