OK found the bug with help from Mike from Hobbytronics. I was running the code on IDE 1.8.2. I found that by declaring the variable assigned to the 3rd AnalogRead (in my case z) to float instead of int the sketch would work. Because of memory I don't like doing that and tried IDE 1.6.0. This resolved the problem as all variables can now be declared as int. I don't know if the bug is present in other IDE versions but at least you could always fall back to the 1.6.0 version if and when necessary.