I would regard code which directly performs a comparison between a float
and a double
without a typecast to be broken; even if the language spec says that the float
will be implicitly converted, there are two different ways that the comparison might sensibly be performed, and neither is sufficiently dominant to really justify a "silent" default behavior (i.e. one which compiles without generating a warning). If one wants to perform a conversion by having both operands evaluated as double
, I would suggest adding an explicit type cast to make one's intentions clear. In most cases other than tests to see whether a particular double
->float
conversion will be reversible without loss of precision, however, I suspect that comparison between float
values is probably more appropriate.
Fundamentally, when comparing floating-point values X
and Y
of any sort, one should regard comparisons as indicating that X
or Y
is larger, or that the numbers are "indistinguishable". A comparison which shows X
is larger should be taken to indicate that the number that Y
is supposed to represent is probably smaller than X
or close to X
. A comparison that says the numbers are indistinguishable means exactly that. If one views things in such fashion, comparisons performed by casting to float
may not be as "informative" as those done with double
, but are less likely to yield results that are just plain wrong. By comparison, consider:
double x, y;
float f = x;
If one compares f
and y
, it's possible that what one is interested in is how y
compares with the value of x
rounded to a float, but it's more likely that what one really wants to know is whether, knowing the rounded value of x
, whether one can say anything about the relationship between x
and y
. If x
is 0.1 and y
is 0.2, f
will have enough information to say whether x
is larger than y
; if y
is 0.100000001, it will not. In the latter case, if both operands are cast to double, the comparison will erroneously imply that x
was larger; if they are both cast to float, the comparison will report them as indistinguishable. Note that comparison results when casting both operands to double
may be erroneous not only when values are within a part per million; they may be off by hundreds of orders of magnitude, such as if x=1e40 and y=1e300. Compare f
and y
as float
and they'll compare indistinguishable; compare them as double
and the smaller value will erroneously compare larger.