/*
============================================================
Title: Generating a Range of Floating-Point Numbers in Swift
============================================================
Swift ranges (e.g., 0...10) work naturally with integer types,
but they do not support stepping through Double values directly.
Best Practice:
Generate an integer range first and transform each element
into the desired floating-point value. This approach is
predictable, readable, and helps avoid floating-point
accumulation errors.
*/
import Foundation
// ------------------------------------------------------------
// Example 1: Generate values from 0.0 to 1.0
// ------------------------------------------------------------
//
// Create an integer range from 0 to 10 and convert each
// value into a Double by dividing by 10.0.
//
// Result:
// 0.0, 0.1, 0.2, ..., 1.0
//
let range1: [Double] = (0...10).map {
Double($0) / 10.0
}
print("Range 1:")
print(range1)
// ------------------------------------------------------------
// Example 2: Generate a custom floating-point range
// ------------------------------------------------------------
//
// Goal:
// Generate values from 1.5 to 3.0 with a step size of 0.25.
//
let start = 1.5
let end = 3.0
let step = 0.25
// Calculate how many increments are needed.
let numberOfSteps = Int(round((end - start) / step))
let range2: [Double] = (0...numberOfSteps).map { index in
start + Double(index) * step
}
print("\nRange 2:")
print(range2)
// ------------------------------------------------------------
// Example 3: Lazy generation using a sequence
// ------------------------------------------------------------
//
// Useful when generating very large ranges because values
// are produced only when needed.
//
let lazySequence = sequence(first: 0.0) { previousValue in
previousValue + 0.5
}
print("\nLazy Sequence:")
for value in lazySequence.prefix(10) {
print(value)
}
/*
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 Sequence:
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
*/