scala - How to overwrite NaN or Infinity result when performing arithmetic on Double? -
I am running a calculation on a group of numbers and returns some result of the results of the result NaN After checking
or infinity
, I came to know that the root cause is due to the arithmetic division below:
object doublefin {println ("in scalable worksheet Welcome ") // // Welcome to Scala Worksheet Val D1 = 0.0 /> & gt; D1: Double = 0.0Wall D2 = 0.0 / // & gt; D2: double = 0.0 wal d = d1 / d2 // & gt; D: Double = Nine Vel I1 = 1.0 // & gt; I1: Double = 1.0 Wall i2 = 0.0 // & gt; I2: double = 0.0 wal i = i1 / i2 // & gt; I: double = infinity wall o1 = 0 // & gt; O1: Int = 0 Well O2 = 0 // & gt; O2: int = 0 well o = o1 / o2 / // & gt; Java.lang.ArithmeticException: / by zero}
I think why NaN
and infinity
are coming back in these cases There is a math question but it is interesting that 0/0
returns a arithmetic exception
while the 0.0 / 0.0
does not?
I 'Using the result of these calculations to descend like a minaret: NaN
& amp; Infinity
The result is in those elements that I want to finalize them.
How can I ensure that NaN
or infinity
for any calculation that is shown when it is sorted ? Can I check NaN
or infinity
inside the result of the calculation and if it is satisfied then 0.0
:
if (D == Double Infinity || D == Double.NAN) {return 0.0}
Nyan
and one exception is actually a more general question, which has been explained.
It is not clear how are you sorting your way, but by default the positive and negative infinite are in the correct type order, and NaN
the last (in ascending order) Comes to:
scala & gt; List (Double Positive Infiniti, Double NGT Infinity, Double. NN, 0.0, -1.0, 2.0). Sets Race 15: List [Double] = List (-Infinity, -1.0, 0.0, 2.0, Infinity, NN) < / Code>
Any easy way to modify behavior will be to map and match a list before sorting.
val list = list (double.postinfiniti, double.ngt infiniti, double_n, 0.0, -1.0, 2.0) list.map {case d if (d.isNaN) = & gt; 0.0 / / or the price you want Case D. If (DICNGIFINITY) = & gt; 0.0 / / or the price you want Case D. (D.IspceInfinity) => 0.0 / / or the value you want is case D = & gt; D} first in the ascending order, double negative infinity
comes first, then all ascertained real numbers, then is repeated. With PositiveInfinity
NaN
if you want both PositiveInfinity
and NegativeInfinity
as well as NaN
to come in the last order, you can map them all to double. NGTifinity
.
Comments
Post a Comment