Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,567 questions

56,785 answers

573 users

How to generate a range of floating-point numbers in Scala

1 Answer

0 votes
/*
 * ============================================================
 * 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

*/



answered Oct 7 by avibootz
...