2015-04-22 53 views
2

我的任务是编写一个名为random_line的函数,该函数为具有正态分布N(0,σ^ 2)的y方向随机噪声的线创建x和y数据: y = mx + b + N(0,σ^ 2)。用高斯噪声绘制线

我现在的问题是更多的数学相关的猜测,而不是编程相关。为了创建我的ydata点,我猜我必须将我的x数据点数组插入到上面的等式中。但是,我不知道如何计算N(0,σ^ 2)部分。有任何想法吗?

def random_line(m, b, sigma, size=10): 
    """Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0] 

    Parameters 
    ---------- 
    m : float 
     The slope of the line. 
    b : float 
     The y-intercept of the line. 
    sigma : float 
     The standard deviation of the y direction normal distribution noise. 
    size : int 
     The number of points to create for the line. 

    Returns 
    ------- 
    x : array of floats 
     The array of x values for the line with `size` points. 
    y : array of floats 
     The array of y values for the lines with `size` points. 
    """ 
    xdata = np.linspace(-1.0,1.0,size) 
    ydata = 'xxxxxxx' 
    return xdata, ydata 
+0

退房'scipy.stats'为从不同分布产生值的方法,对于你想要的随机正态分布值'scipy.stats.norm.rvs(size = whatever) – Marius

回答

0

检出Python标准库中的random.normalvariate。

1

scipy.stats使用分布很容易创建的方式,让您可以轻松将其添加到您的其他numpy的阵列状xdata常分布的错误:

import scipy.stats 
import numpy as np 
import matplotlib.pyplot as plt 

def random_line(m, b, sigma, size=10): 
    xdata = np.linspace(-1.0,1.0,size) 
    # Generate normally distributed random error ~ N(0, sigma**2) 
    errors = scipy.stats.norm.rvs(loc=0, scale=sigma, size=size) 
    ydata = m * xdata + b + errors 
    return xdata, ydata 

xs, ys = random_line(2, 3, 2, size=50) 

# Plot to see how closely the values fit the 
# original line 
fig, ax = plt.subplots() 
ax.plot(xs, ys, 'o') 
ax.plot(xs, 2 * xs + 3)