Anxiety and stress can cause a magnesium deficiency. I don't take the supplement but I do try to get it from my diet and Epsom salt (contains magnesium sulfate) in bath water.
According to Dr. Hyman's blog, "Avoid magnesium carbonate, sulfate, gluconate, and oxide. They are poorly absorbed (and the cheapest and most common forms found in supplements)." Maybe the supplement you are taking is in one of those forms and that is why you have terrible gas. It also says, "The most absorbable forms are magnesium citrate, glycinate taurate, or aspartate, although magnesium bound to Kreb cycle chelates (malate, succinate, fumarate) are also good."
Here is the link to his blog:
http://www.ultrawellness.com/blog/magnesium-relaxation-mineral
There is quite a bit of info about magnesium.
You can also watch him on Youtube here.
I really like this doctor but he does talk fast which some people find annoying and anxiety provoking.