1

Have two arrays of Doubles, I want to compare them and create a new array with result of the difference, but not sure how to create a loop for that. Please advise.

Example of the arrays here:

 var freshRates = [1.6,1.7,2.0]
 var oldRates = [1.5,1.4,1.9]
 var difference: [Double] = []
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Ula
  • 167
  • 1
  • 2
  • 11
  • 2
    Compare https://stackoverflow.com/questions/39724115/swift-how-to-multiply-array-by-array-math-vector-by-vector for a similar question with different solutions. – In your case that would be `let difference = zip(freshRates, oldRates).map(-)` – Martin R Jan 24 '18 at 10:10
  • Thank you for the info, just not found that one by key words first time. – Ula Jan 24 '18 at 10:20

2 Answers2

1

Zip the arrays to get an array of tuples, and then just use map to calculate difference for each pair:

var freshRates = [1.6,1.7,2.0]
var oldRates = [1.5,1.4,1.9]
var difference: [Double] = zip(freshRates, oldRates).map({ $0.0 - $0.1 })
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
  • Thank you again @Milan for the solution ,really appreciated for the help with my project only one more question, it possible to reduce amount of numbers after . because right now in the print it's giving result [0.10000000000000009, 0.30000000000000004, 0.10000000000000009] – Ula Jan 24 '18 at 10:12
  • @Ula: That is explained in https://stackoverflow.com/questions/40959254/why-are-doubles-printed-differently-in-dictionaries (which is about floating point numbers in dictionaries, but applies to arrays as well). The basic reason is that `0.1` *cannot* be represented exactly as a binary floating point number. See also https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Martin R Jan 24 '18 at 10:15
  • @Ula I was just about to reply, when Martin R commented - so just read linked answer. you would get the same result in `let result: Double = 1.6 - 1.5`.. the reason it is printed as that is a result of printing the whole array, if you print just `difference[0]`, it will print `0.1` - I am not sure why the array's string description presents like that – Milan Nosáľ Jan 24 '18 at 10:17
  • 1
    @MilanNosáľ: That is because printing an array (or dictionary) uses `debugPrint()` to print its elements, compare https://stackoverflow.com/a/40959459. – Martin R Jan 24 '18 at 10:19
  • 2
    Thank you both for the support in this question. – Ula Jan 24 '18 at 10:22
1
var freshRates = [1.6,1.7,2.0]
var oldRates = [1.5,1.4,1.9]
var difference: [Double] = []

for (val1,val2) in zip(freshRates, oldRates){
    difference.append(val2 - val1)
}

debugPrint(difference)
Reinier Melian
  • 20,519
  • 3
  • 38
  • 55