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 ?

2
  • 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"? Commented Jun 14, 2018 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. Commented Jun 14, 2018 at 10:41

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

5 Comments

@vacawama : Plane n simple +1
Sorry another rookie mistake :P
Perhaps one should mention that this can produce “unexpected” results if the numbers are not exactly representable as binary floating point numbers. An example would be Array(stride(from: 0, through: 0.7, by: 0.1)), which evaluates to [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001]
Thanks @MartinR, I was thinking of doing that, but I was failing to find a nice concise example.
Thanks, you save my day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.