Printed double value differs from originally set value

后端 未结 3 439
慢半拍i
慢半拍i 2021-01-25 15:52

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)\");
         


        
3条回答
  •  隐瞒了意图╮
    2021-01-25 16:25

    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:

提交回复
热议问题