Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Specific Float Array with Int range

Tags:

arrays

swift

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 ?

like image 269
Gauthier Beignie Avatar asked Jun 14 '18 10:06

Gauthier Beignie


People also ask

How to generate a float number range in Python?

You can define a generator to replicate the behavior of Python’s built-in function range () in such a way that it can accept floating-point numbers and produces a range of float numbers. The following code divided into 2 Sections.

What is the range of float in Java?

A float is a Java data type which can store floating point numbers (i.e., numbers that can have a fractional part). Only 4 bytes are used to store float numbers giving a value range of -3.4028235E+38 to 3.4028235E+38.

What is float array in Java?

Java float array is used to store float data type values only. The default value of the elements in a Java float array is 0. With the following Java float array examples you can learn

How do you find the length of a float range?

You can determine the size by subtracting the start value from the stop value (when step = 1). Below is the general formula to compute the length. Check some examples to get clarity. However, the same range virtually has an infinite no. of float numbers. You can restrict it by using a fixed precision value.


1 Answers

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 }
like image 144
vacawama Avatar answered Nov 03 '22 09:11

vacawama