This week's book giveaway is in the Agile forum. We're giving away four copies of The Software Craftsman and have Sandro Mancuso on-line! See this thread for details.

I have read in the Java Language Specification 2nd Edition that floating point operations might be imprecise. Let's this code snippet:

I get this output:

Square Root: 1.4142135623730951 Second Power: 2.0000000000000004 Not Equal

So, what should I do when working with floating-point numbers to make sure the calculations are appropriate. Above all in the scientific and financial applications?

I did some scientific programming years ago. The two ways I checked for equality were to compare the absolute value of the difference to a small number and (more accurately) to subtract 1.0 from the quotient and compare the absolute value to a small number.

For financial applications, double is for homework. Real applications use BigDecimal.