我使用scala Range.by來分割一個範圍來獲得一個數組,但它錯過了某個特殊的bucket num的最後一個,例如100.我感到困惑,並且演示如下:scala範圍split缺少最後一個
object SplitDemo extends App {
val min = 0.0
val max = 7672.142857142857
val bucketNum = 100
def splitsBucket1(min: Double, max: Double, num: Int) = (min to max by ((max - min)/num)).toArray
def splitsBucket2(min: Double, max: Double, num: Int): Array[Double] = {
val rst = Array.fill[Double](num + 1)(0)
rst(0) = min
rst(num) = max
val step = (max-min)/num
for(i <- 1 until num) rst(i) = rst(i-1)+step
rst
}
val split1 = splitsBucket1(min, max, bucketNum)
println(s"Split1 size = ${split1.size}, %s".format(split1.takeRight(4).mkString(",")))
val split2 = splitsBucket2(min, max, bucketNum)
println(s"Split2 size = ${split2.size}, %s".format(split2.takeRight(4).mkString(",")))
}
輸出以下
分割1大小= 100,7365.257142857143,7441.978571428572,7518.700000000001,7595.421428571429
Split2大小= 101,7441.978571428588,7518.700000000017,7595.421428571446,7672.142857142857
當num = 100時,split1 錯過了最後一個,但是split2沒有(這是我的期望)。當num是其他num時,e.t. 130,split1和split2得到樣本結果。
有什麼理由貶低這種差異?
你試過調試嗎? –