1

I am adding two array which contains double values

 let arrayA = [1.1,2.3]
 let arrayB = [4.2,5.5,6.8]

 let c = arrayA + arrayB

 print("\(c)");

The print function is printing following result :

[1.1000000000000001, 2.2999999999999998, 4.2000000000000002, 5.5, 6.7999999999999998]

How to get exact double values after adding arrays ?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Abhishek Gupta
  • 601
  • 5
  • 16
  • 2
    its called precision value you can control using %.2f .. – vaibhav Nov 10 '16 at 11:14
  • Compare also [Why are doubles printed differently in dictionaries?](https://stackoverflow.com/questions/40959254/why-are-doubles-printed-differently-in-dictionaries) – this is the same issue. – Martin R Dec 22 '17 at 07:42

3 Answers3

4

You don't. It's the way Double (and Float) does work.

As workaround you can round your values when you are going to print them

for num in c {
    print(String(format: "%.1f", num))
}

1.1

2.3

4.2

5.5

6.8

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

You need to change as below :

defind type of array because you have not defined at now .

 let arrayA : [CGFloat] = [1.1,2.3]
 let arrayB : [CGFloat] = [4.2,5.5,6.8]
KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • @shallowThought did you check output ? – KKRocks Nov 11 '16 at 04:36
  • @shallowThought i have check output after that i have posted my answer . – KKRocks Nov 11 '16 at 04:40
  • You are right. I understood the question as "why does 1.1(0000000) become 1.00000001. You are fixing the printed format. Can notre -upvote as "the vote is locked until the answer is updated". Sorry. Happy coding! – shallowThought Nov 11 '16 at 10:40
1

The reason for what you are seeing (1.1 -> 1.1000000000000001) lies in the nature of floating points. It is caused by rounding errors, as the infinite nature of real numbers can not be presented in its finite memory (floating point) representation.

This might not be a big issue in your case, as you can change the printed format as stated in other answers, but can cause hard to track bugs, especially when comparing floating point numbers. For instance, the following code:

let result = 1.1 * 3.0

if result == 3.3 {
    print("I thought so!")
} else {
    print("This might be unexpected")
}

prints:

This might be unexpected

For more information I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic:

shallowThought
  • 19,212
  • 9
  • 65
  • 112