This is a terrible way to do IK. It is numerically unstable and will give vastly different solutions upon slight changes to the input. Coordinated Cyclic Descent using twist and swing quaternions give much better results:
http://www.tandfonline.com/doi/abs/10.1080/2165347X.2013.823...