The built-in digital compass works just like a magnetic-needle compass. The accuracy of digital compass headings can be affected by magnetic or other environmental interference, including interference caused by proximity to the magnets contained in the iPhone earbuds. The compass may need to be calibrated from time to time.
Please refer to Apple's Support Document for more details.
http://support.apple.com/kb/TS2767
Incidentally, we have found this clip to show to the most effective way to re-calibrate the compass...