NaN可能出现的情况-Scala

scala 中出现NaN的情况

  1. 当表达式的一个或多个操作数是NaN时,其结果也是NaN.
  2. 0.0/0.0其结果是NaN.
  3. 当0做为除数时会报除零错误;当0.0(double or float)做除数是结果是无穷或者NaN.
  4. Infinity与Infinity之间的运算,结果可能为Infinity也可能为NaN,Infinity/Infinity = NaN.
  5. Infinity与0.0进行+,-,/结果为Infinity或者0,Infinity与0相乘结果为NaN.

下面就Scala中可能出现NaN的情况给出一些示例:

// 除float or double 0 得到无穷(正无穷或负无穷)或NaN
import scala.math
val a1 = 1.0/0.0
val a2 = 2.0/0.0
val b1 = -1.0/0.0
val b2 = -2.0/0.0
val c = 0.0/0d     // 零 除零 结果是 NaN

//output
a1 = Infinity
a2 = Infinity
b1 = -Infinity
b2 = -Infinity
c = NaN

//非浮点类型的0作为除数会抛出错误而不是得到无穷或者NaN 
val d1 = 2/0
val d2 = 2.0/0
//output
Name: java.lang.ArithmeticException
Message: / by zero
StackTrace:
...

// 无穷之间的运算得到无穷或者NaN
val e1 = a1 + a2
val e2 = a1 - a2  // (+Infinity) - (+Infinity) = NaN
val e3 = a1 / a2  // (+Infinity) / (+Infinity) = NaN
val e4 = a1 * a2
//output
e1 = Infinity
e2 = NaN
e3 = NaN
e4 = Infinity

val f1 = b1 + b2
val f2 = b1 - b2  // (-Infinity) - (-Infinity) = NaN
val f3 = b1 / b2  // (-Infinity) / (-Infinity) = NaN
val f4 = b1 * b2
//output
f1 = -Infinity
f2 = NaN
f3 = NaN
f4 = Infinity

// 正无穷和负无穷之间的运算
val g1 = a1 - b1
val g2 = a1 + b1  // (+Infinity) + (-Infinity) = NaN
val g3 = a1 * b1
val g4 = a1 / b1  // (+Infinity) / (-Infinity) = NaN
//output
g1 = Infinity
g2 = NaN
g3 = -Infinity
g4 = NaN

// 无穷数参与对数和指数运算
import scala.math
val h1 = math.log(a1)
val h2 = math.log(0.0)
val h3 = math.log(b1)   // log(-Infinity) = NaN
//output
h1 = Infinity
h2 = -Infinity
h3 = NaN

val t1 = math.exp(a1)
val t2 = math.exp(b1)
//output
t1 = Infinity
t2 = 0.0

val y1 = a1/0.0
val y2 = a2/0        //当无穷数除0时,0可以是任意类型的零(浮点数或者整型)
val y3 = 0/a1
val y4 = 0.0/a1
val y5 = a1 + 0.0
val y6 = 0 - a1
val y7 = 0.0 * a1         // 0 * Infinity = NaN
//output
y1 = Infinity
y2 = Infinity
y3 = 0.0
y4 = 0.0
y5 = Infinity
y6 = -Infinity
y7 = NaN

// 无穷与无穷之间的指数运算
val a = 1.0 / 0.0
val b = -2.0 / 0.0
import scala.math
val c1 = math.pow(a,b)
val c2 = math.pow(a,-b)
//output
a = Infinity
b = -Infinity
c1 = 0.0
c2 = Infinity

你可能感兴趣的:(NaN可能出现的情况-Scala)