Posted by

cayhorstmann on August 14, 2011 at 5:14 PM PDT

I am in the process of revising a CS1 textbook. I made changes requested by users, added snazzy exercises and sample programs, and the publisher sent the draft out to reviewers. A couple of reviewers said in no uncertain terms that I was wrong, wrong, wrong in using double for my examples. I should use float instead. Another professor contributed a business problem set that used float where I would have used double, or, if I had been allowed, BigDecimal. What gives? Am I missing the boat on float?

I am in the process of revising a CS1 textbook. I made changes requested by users, added snazzy exercises and sample programs, and the publisher sent the draft out to reviewers. A couple of reviewers said in no uncertain terms that I was wrong, wrong, wrong in using `double`

for my examples. I should use `float`

instead. Another professor contributed a business problem set that used `float`

where I would have used `double`

, or, if I had been allowed, `BigDecimal`

.

What gives? For financial calculations, `float`

aren't so wonderful. For example,

`float unitPrice = 34999.95F;`

int quantity = 199;

float totalPrice = unitPrice * quantity; // Off by five cents from the correct value

Clearly, `BigDecimal`

would be the right choice, but they are awful to use in Java.

`BigDecimal unitPrice = new BigDecimal("34999.95");`

BigDecimal quantity = new BigDecimal("199");

BigDecimal totalPrice = unitPrice.multiply(quantity);

In Scala, you could write `BigDecimal("34999.95") * 100`

. But that doesn't help me. Nobody uses Scala for their introductory course. Anyway, reviewers were adamant not to use objects and method calls too early. So, `BigDecimal`

wasn't going to fly. But I digress.

Back to `float`

. Even if you don't care about limited precision, they are also awkward. You have to remember to put `F`

after each literal, and you have to cast the results of mathematical methods:

`float goldenRatio = 0.5`**F** * (1 + **(float)** Math.sqrt(5))

For what? Saving four bytes? In a student program that gets executed a handful of times?

I can see the use of `float`

in a 1000 x 1000 matrix, if the added precision isn't needed, to save the storage. Does it save time? I seem to recall that in an Intel processor, when both `float`

and `double`

get extended unless you use `strictfp`

. No reviewer had requested that I cover that :-)

Am I missing the boat here? Is there another reason to use `float`

in this day and age, other than saving storage when you have a lot of them? I read through What Every Computer Scientist Should Know About Floating-Point Arithmetic , and was not enlightened. If you use `float`

, can you tell me why?