title: Numerical evaluation of arctangent functions
body: <p>I am having difficulties to interpret results of arctangent functions. This behaviour is consistent for all implementations I came across, so I will here limit myself to NumPy and MATLAB.</p>
  <p>The idea is to have circle of randomly placed points. The goal is to represent their positions in polar coordinate system and since they are uniformly distributed, I expect the θ angle (which is calculated using <code>atan2</code> function) to be also distributed randomly over interval -π ... π.</p>
  <p>Here is the code for MATLAB:</p>
  <pre><code>stp = 2*pi/2^8;
  siz = 100;
  num = 100000000;
  
  x = randi([-siz, siz], [1, num]);
  y = randi([-siz, siz], [1, num]);
  m = (x.^2+y.^2) &lt; siz^2;
  
  [t, ~] = cart2pol(x(m), y(m));
  figure()
  histogram(t, -pi:stp:pi);
  </code></pre>
  <p>And here for Python &amp; NumPy:</p>
  <pre><code>import numpy as np
  import matplotlib.pyplot as pl
  
  siz = 100
  num = 100000000
  
  rng = np.random.default_rng()
  x = rng.integers(low=-siz, high=siz, size=num, endpoint=True)
  y = rng.integers(low=-siz, high=siz, size=num, endpoint=True)
  m = (x**2+y**2) &lt; siz**2
  
  t = np.arctan2(y[m], x[m]);
  pl.hist(t, range=[-np.pi, np.pi], bins=2**8)
  pl.show()
  </code></pre>
  <p>In both cases I got results looking like this, where one can easily see &quot;steps&quot; for each multiple of π/4.</p>
  <p><a href="https://i.stack.imgur.com/3lXBS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3lXBS.png" alt="Atan2 results" /></a></p>
  <p>It looks like some sort of precision error, but strangely for angles where I would not expect that. Also this behaviour is present for ordinary <code>atan</code> function as well.</p>