0

I'v tried following code when learning the mutation function of structure type

struct SelfMutaPoint {
        var x = 0.0, y = 0.0 
        mutating func moveBy(x deltaX: Double, y deltaY: Double) {
                self = SelfMutaPoint(x: x + deltaX, y: y + deltaY)
        }   
}

var someSelfMutaPoint = SelfMutaPoint()
someSelfMutaPoint.moveBy(x: 1.3, y: 3.4) //print "SelfMutaPoint(x: 1.3, y: 3.3999999999999999)\n"
print(someSelfMutaPoint)

print(0.0 + 3.4) // print "3.4\n"

Question:

It is the same operation (0.0 + 3.4) I've applied on, why the operation inside SelfMutaPoint method would leads to a different precision than it placed inside the print function of which from the standard library? (please see the comments in the code above)

Note: It always has "problems" with x.4 digits, I guess it has something to do with how rounding works in computer.

Many Thanks

SLN
  • 4,772
  • 2
  • 38
  • 79
  • 1
    It's not the problem of calculation precision or sort of rounding. It just a problem of how default format is chosen. When printing `Double`, Swift chooses normal rounded format. When printing struct without `description`, Swift chooses "debug format" which avoid rounding for `Double` members. – OOPer Oct 16 '16 at 10:53
  • 1
    It is the same issue as in http://stackoverflow.com/questions/39770303/swift-issue-in-converting-string-to-double: `description` and `debugDescription` use a different precision for the conversion. – Martin R Oct 16 '16 at 10:54
  • 1
    Try `print(someSelfMutaPoint.y)` or `print(0.0 + 3.4 == someSelfMutaPoint.y)`. `someSelfMutaPoint.y` contains exactly the same value as `0.0 + 3.4`. – OOPer Oct 16 '16 at 10:55
  • @OOPer Thanks a lot for your short and nice explanation. it works! – SLN Oct 16 '16 at 11:03
  • @MartinR Thanks for the URL link – SLN Oct 16 '16 at 11:03

0 Answers0