How to detect Infinity values in Scala?
Solution 1
Scala's Double
has an isInfinite
method, and Neg
/Pos
variants:
scala> val a = 22.0
a: Double = 22.0
scala> a.isInfinite
res0: Boolean = false
scala> val b = 2.0/0
b: Double = Infinity
scala> b.isInfinite
res1: Boolean = true
scala> b.isPosInfinity
res4: Boolean = true
Solution 2
What everyone else has said, plus this: the reason for the separate isNaN
is that comparison with NaN
is special:
scala> val bar = Double.NaN
bar: Double = NaN
scala> bar == Double.NaN
res0: Boolean = false
No such rules apply for infinity, so there is no need for a special check function (except for the convenience of handling the sign):
scala> val foo: Double = Double.PositiveInfinity
foo: Double = Infinity
scala> foo == Double.PositiveInfinity
res1: Boolean = true
Solution 3
The method actually is there. It's just called isInfinity
instead of isInf
.
See scaladocs for RichDouble
line 36: https://github.com/scala/scala/blob/v2.10.2/src/library/scala/runtime/RichDouble.scala#L36
akauppi
Loves hiking, sailing and developing LEGO CAD models. Also: modern agile HR (especially feedback loops) making work bearable for everyone making the team shine!!! Previously (2015-18): P&O Engineer at Zalando … Current (Dec/2021-): Data Steward at Relex Solutions
Updated on June 14, 2022Comments
-
akauppi almost 2 years
Scala has
Double.isNaN
for detecting not-a-number but noDouble.isInf
for detecting (positive or negative) infinity.Why? I'd like to check whether a parameter is a "real" number (i.e. has a numeric value). Converting it to a string and checking for "inf" or something will do it, but there must be a better way?
Like in C++: http://en.cppreference.com/w/cpp/numeric/math/isinf
Using Scala 2.10
-
akauppi almost 11 yearsThanks. Don't know how I missed it.
-
akauppi almost 11 yearsThanks. What I find slightly confusing is that Double.PositiveInfinity uses the (too) long wording, whereas Double.isPosInfinity uses a shorter one.
-
som-snytt almost 11 years@akauppi Maybe because the REPL doesn't autocomplete it. I see eclipse will offer it.
-
gourlaysama almost 11 years@som-snytt oh, good point. IDEA does show them. (I think the Netbeans plugin too)