Reputation: 27373
I'm working in a code where Double-values are compared to a predefined Constant marking a missing value. This value is used in a way that it is assigned to variables (here input
) if they don't fulfil certain requirements:
val BAD = -9999.9
val verified = if(isQualityOk(input)) input else BAD
Later in the application, the numbers are again checked whether they are good or not:
if(!myNumber.equals(BAD)) {
// do something with it
}
I'm aware that it is generally a bad idea to compare Float/Double values using "equals" because of rounding errors (finite machine precision), therefore it's recommended to compare the absolute value of their difference being under a certain limit.
My question: Is this also necessary in my above example where no arithmetics is done with the numbers? Or is it safe in this case to use the implementation of Double#equals
?
Upvotes: 0
Views: 888
Reputation: 5315
If you do no floating-point operation on your Double
s, it should be fine.
However, this is not how you should handle special cases in functional programming.
It would be probably more explicit to do something like the following:
val verified: Option[Double] = Some(input).filter(isQualityOk)
so that the type system tells you that you are not sure to have a valid value (it will be None
if the quality is not OK).
If you usually apply a function f(d: Double): T
to verified
, just do verified.map(f)
, to get an Option[T]
, and keep going on.
Whenever you need a real value, you can always get back to Double
by doing verfied.getOrElse(BAD)
, but it is better to keep the exceptional case as None
as long as possible, so that the type system can help you avoid some errors.
Upvotes: 1
Reputation: 2739
If there are no calculations, then there is no place where you can lose precision (except for the conversion from decimal number to binary one). So you should be good.
Having said that - this is the kind of code that 2-3 versions down the road will generate some subtle bugs because of the response you mention, so if this code will go in a code that should be kept viable in the long run, I'd re-arrange things to use a safer data type (verified
sound like it should be a Boolean
, no?)
Upvotes: 0