0

I typed this code in Swift playground (Xcode 7.3.1) to see how functions treat their parameters as constants. We are required to add var in front of a parameter's name if we want to change its value. However, I was surprised to see the result of a simple subtraction. Can someone explain why I am getting 0.5999999999999996 instead of 0.6? Here is the code:

func subtract(var x: Double, from y: Double) -> Double {
    x = x + 1.0
    return y - x
}

let result = subtract(3.2, from: 4.8) // result: 0.5999999999999996
Ranjan
  • 1
  • 3
  • Also `var` function parameters are deprecated, and will be removed in Swift 3. You'll need to create your own shadow variable (i.e `var x = x`). – Hamish Jun 02 '16 at 18:41
  • Thanks for pointing that out. I don't see the reason though. I tried this code in Java too and got the same answer. If possible, I would like to leave this question in as someone searching specifically for Swift accuracy should be able to see it even though it's a general floating point issue. – Ranjan Jun 02 '16 at 18:50
  • Sure, duplicates are [intended to act as signposts for future visitors](http://meta.stackexchange.com/questions/230/duplicate-question-etiquette-to-delete-or-not-to-delete) and are therefore usually not deleted. – Hamish Jun 02 '16 at 18:59

0 Answers0