Generate data with normally distributed noise and mean function
<p>I created a numpy array with n values from 0 to 2pi. Now, I want to generate n test data points deviating from sin(x) normally distributed. </p>

<p>So i figured I need to do something like this: <code>t = sin(x) + noise</code>. Where the noise must be something like this: <code>noise = np.random.randn(mean, std)</code>.</p>

<p>However, I do not know how I can calculate the noise when my mean is sin(x) (and not a constant).</p>

<p>The arguments to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html" rel="nofollow"><code>numpy.random.randn</code></a> are not the mean and standard deviation.  For that, you want <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html" rel="nofollow"><code>numpy.random.normal</code></a>.  Its signature is</p>

<pre><code>normal(loc=0.0, scale=1.0, size=None)
</code></pre>

<p>To add noise to your sin function, simply use a mean of 0 in the call of <code>normal()</code>.  The mean corresponds to the <code>loc</code> argument (i.e. "location"), which by default is 0.  So, given that <code>x</code> is something like <code>np.linspace(0, 2*np.pi, n)</code>, you can do this:</p>

<pre><code>t = np.sin(x) + np.random.normal(scale=std, size=n)
</code></pre>

<hr>

<p>You <em>could</em> use <code>numpy.random.randn</code>, but you have to scale it by <code>std</code>, because <code>randn</code> returns samples from the standard normal distribution, with mean 0 and standard deviation 1.  To use <code>randn</code>, you would write:</p>

<pre><code>t = np.sin(x) + std * np.random.randn(n)
</code></pre>

python numpy scipy normal-distribution