5

Is there ever a case where these two methods would return different values given the same inputs?

int compare1(float a, float b)
{
    return Double.compare(a, b);
}

int compare2(float a, float b)
{
    return Float.compare(a, b);
}

By the same token, is it true (or false) that any number storable in a java's Float can be stored in a java's Double without losing any precision?

Thanks

user1508893
  • 9,223
  • 14
  • 45
  • 57

3 Answers3

8

Yes; casting doubles to floats can yield different results.

If the difference between a and b is too small to show up in a float, compare2() will return 0 whereas compare1() would not.


You just edited the question to reverse what you were asking. The new answer is:

I'm almost certain that they will always be the same.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

Every float can be represented exactly as a double. From this it follows that the two functions always return the same result.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

A double just gives you more bits of precision beyond the decimal place than the float. If all those those extra bits are zero then you have the same value as the float. So yes, all floats can be converted to doubles without losing precision.

Eduardo
  • 8,362
  • 6
  • 38
  • 72