Re: Comparing floating point values in Java
- From: Philipp <sicsicsic@xxxxxxxxxxx>
- Date: Tue, 02 Jan 2007 13:20:03 +0100
Patricia Shanahan wrote:
Daniel Pitts wrote:Eric Sosman wrote:Philipp wrote:[...]Perhaps you can avoid the entire issue by choosing a
I was calculating an array of float values from some user input. But
sometimes (rarely) the calculation cannot be done (this is correct
behavior).
I then want to mark these values by setting them to -1 and treat this
special case later on. So I later need to test for -1 in my array.
different "distinguished value." Float.NaN, maybe, using
the Float.isNaN(float) method instead of an == test. (NaN
seems a more natural surrogate for "does not compute," too.)
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx
Or even have a seperate boolean array to specify valid results.
Having a magic value isn't generally a good idea, although NaN would be
the way to go if you did.
Since the special cases are rare, one could also describe them by having
e.g. a HashSet<Integer> containing the index values of the special cases.
Using any magic value, including NaN, has the risk that a bug elsewhere
in the code will get hidden as the special case. The risk can be reduced
by using a specific NaN value and Float.floatToRawIntBits to check for it.
Thanks for pointing out the NaN possibility which I did not think of before and is really more "beautiful".
The two other possibilities (using a separate array to mark the bad values and using a hashset with indexes of bad values) seemed a bit overkill at first. But maybe this is really the cleaner way to go.
Happy New Year
Phil
.
- Prev by Date: Re: java
- Next by Date: Re: Unable to Include Images in the HTML file
- Previous by thread: Re: Comparing floating point values in Java
- Next by thread: Re: Unable to Include Images in the HTML file
- Index(es):
Relevant Pages
|