6

I would like to generate an Array with all Integers and .5 values with an Int Range. The result wanted :

min value = 0

max value = 5

generated Array = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]

I know how to get only the integers value :

Array(0...5)

But not this one with float values ... I think is clear enough, anyone has an idea ?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 1
    Is 0.5 supposed to be the only step in between, or is 0.123 another valid step size? Upper and lower bound are inclusive? What is the expected outcome for "from 0, to 1, size 0.3"? – luk2302 Jun 14 '18 at 10:31
  • I think OP wants to get only `integer` value from `[0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]` array not .5 interval value. – Pankil Jun 14 '18 at 10:41

1 Answers1

14

Use Array() with stride(from:through:by:):

let arr = Array(stride(from: 0, through: 5, by: 0.5))
print(arr)
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

If your min and max values truly are Int, then you'll need to convert them to Double:

let min = 0
let max = 5
let step = 0.5

let arr = Array(stride(from: Double(min), through: Double(max), by: step))

Warning:

Due to the nature of floating point math, this can possibly lead to unexpected results if the step or endpoints are not precisely representable as binary floating point numbers.

@MartinR gave an example:

let arr = Array(stride(from: 0, through: 0.7, by: 0.1))
print(arr)
[0.0, 0.10000000000000001, 0.20000000000000001, 0.30000000000000004, 0.40000000000000002, 0.5, 0.60000000000000009]

The endpoint 0.7 was excluded because the value was slightly beyond it.

You might also want to consider using map to generate your array:

// create array of 0 to 0.7 with step 0.1
let arr2 = (0...7).map { Double($0) / 10 }

That will guarantee that you capture the endpoint 0.7 (well, a close approximation of it).

So, for your original example:

// create an array from 0 to 5 with step 0.5
let arr = (0...10).map { Double($0) / 2 }
vacawama
  • 150,663
  • 30
  • 266
  • 294