/*
* ============================================================
* Title: Generating a Range of Floating-Point Numbers in Scala
* ============================================================
*
* Scala's Range works only with integral types such as Int and Long.
* To generate floating-point values, create an integer range and
* transform each value into a Double.
*/
object FloatingPointRangeExample {
def main(args: Array[String]): Unit = {
// ----------------------------------------------------------
// Example 1: Generate values from 0.0 to 1.0
// ----------------------------------------------------------
val range1: Seq[Double] =
(0 to 10).map(_.toDouble / 10.0)
println("Range 1:")
println(range1.mkString(", "))
// ----------------------------------------------------------
// Example 2: Custom floating-point range
// ----------------------------------------------------------
val start = 1.5
val end = 3.0
val step = 0.25
// Calculate the number of increments required.
val numberOfSteps =
((end - start) / step).round.toInt
val range2: Seq[Double] =
(0 to numberOfSteps)
.map(i => start + i * step)
println("\nRange 2:")
println(range2.mkString(", "))
// ----------------------------------------------------------
// Example 3: Lazy generation (Scala 2.13+ / Scala 3)
// ----------------------------------------------------------
// LazyList creates elements on demand, making it efficient
// for large or potentially infinite sequences.
val lazyRange: LazyList[Double] =
LazyList.iterate(0.0)(_ + 0.5)
.take(10)
println("\nLazy Range:")
println(lazyRange.mkString(", "))
}
}
/*
run:
Range 1:
0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
Range 2:
1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0
Lazy Range:
0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5
*/