# How does this periodic trig function that calculates modulus work?

$$\arctan(\tan(( \mathrm{dividend} - \frac{\mathrm{divisor}}{2}) \times \frac{\pi}{\mathrm{divisor}}))*\frac{\mathrm{divisor}}{\pi}+\frac{\mathrm{divisor}}{2}= \mathrm{dividend} \bmod \mathrm{divisor}$$

This is a follow up to http://stackoverflow.com/questions/14841280/a-clever-homebrew-modulus-implementation

I'm not sure where to begin to understand how this works. Any suggestions? I know that I'm supposed to tell you what I have tried, but essentially I don't know where to begin.

-
I think there is a small mistake in your formula. The last term on the right hand side should probably be $divisor/2$. – Elmar Zander Feb 14 '13 at 16:15
@ElmarZander you're right. I think I fixed it. – Ben Mordecai Feb 14 '13 at 16:18

I would rewrite it a little bit first. Say you want $a \mod b$ i.e. a real number $r$, such that $0\leq r<b$ and $a=mb+r$ holds for some integer $m$. Your formula can be written as $$a \mod b = r = \arctan(\tan(\frac{a\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2$$ Now enter $a=mb+r$ into that formula and you'll see $$r=\arctan(\tan(\frac{a\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\ =\arctan(\tan(m\pi + \frac{r\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\ =\arctan(\tan(\frac{r\pi}{b}-\frac{\pi}2))\frac{b}\pi + \frac{b}2\\ =(\frac{r\pi}{b}-\frac{\pi}2)\frac{b}\pi + \frac{b}2\\ =r-\frac{b}2 + \frac{b}2\\$$ where I've used that $\tan$ is periodic with period $\pi$ (line 2 to 3) and that $\arctan$ is defined on $[-\pi/2,\pi/2]$ and $\arctan(\tan(x))=x$ on that interval (line 3 to 4).