代码之家  ›  专栏  ›  技术社区  ›  Rohit Pandey

如何在numpy repo中找到方法实现

  •  0
  • Rohit Pandey  · 技术社区  · 8 年前

    我刚刚阅读了生成普通随机变量的Box-Mueller方法,想看看numpy python中的方法是否使用相同的方法。为此,我想看看源代码。我一直在梳理 GitHub repository 但还没有运气。“Random”文件夹似乎没有我感兴趣的代码。特别是,我想要调用时调用的代码-

    import numpy as np
    rand = np.random.normal(size=10)
    

    是否有人能够向我指出代码的这一部分,并大致解释如何有效地执行这些类型的搜索?

    编辑:下面的代码行在这种情况下没有太大帮助,因为它只指向 初始化 .py文件中没有太多内容。

    print(numpy.random.__file__)
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Zev    8 年前

    https://github.com/numpy/numpy/blob/464f79eb1d05bf938d16b49da1c39a4e02506fa3/numpy/random/mtrand/mtrand.pyx#L1551

    random/mtrand/mtrand.pyx .pyx

    normal "def normal"

    def normal(self, loc=0.0, scale=1.0, size=None):
        """
        normal(loc=0.0, scale=1.0, size=None)
        Draw random samples from a normal (Gaussian) distribution.
        The probability density function of the normal distribution, first
        derived by De Moivre and 200 years later by both Gauss and Laplace
        independently [2]_, is often called the bell curve because of
        its characteristic shape (see the example below).
        The normal distributions occurs often in nature.  For example, it
        describes the commonly occurring distribution of samples influenced
        by a large number of tiny, random disturbances, each with its own
        unique distribution [2]_.
        Parameters
        ----------
        loc : float or array_like of floats
            Mean ("centre") of the distribution.
        scale : float or array_like of floats
            Standard deviation (spread or "width") of the distribution.
        size : int or tuple of ints, optional
            Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
            ``m * n * k`` samples are drawn.  If size is ``None`` (default),
            a single value is returned if ``loc`` and ``scale`` are both scalars.
            Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
        Returns
        -------
        out : ndarray or scalar
            Drawn samples from the parameterized normal distribution.
        See Also
        --------
        scipy.stats.norm : probability density function, distribution or
            cumulative density function, etc.
        Notes
        -----
        The probability density for the Gaussian distribution is
        .. math:: p(x) = \\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }}
                         e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} },
        where :math:`\\mu` is the mean and :math:`\\sigma` the standard
        deviation. The square of the standard deviation, :math:`\\sigma^2`,
        is called the variance.
        The function has its peak at the mean, and its "spread" increases with
        the standard deviation (the function reaches 0.607 times its maximum at
        :math:`x + \\sigma` and :math:`x - \\sigma` [2]_).  This implies that
        `numpy.random.normal` is more likely to return samples lying close to
        the mean, rather than those far away.
        References
        ----------
        .. [1] Wikipedia, "Normal distribution",
               https://en.wikipedia.org/wiki/Normal_distribution
        .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
               Random Variables and Random Signal Principles", 4th ed., 2001,
               pp. 51, 51, 125.
        Examples
        --------
        Draw samples from the distribution:
        >>> mu, sigma = 0, 0.1 # mean and standard deviation
        >>> s = np.random.normal(mu, sigma, 1000)
        Verify the mean and the variance:
        >>> abs(mu - np.mean(s)) < 0.01
        True
        >>> abs(sigma - np.std(s, ddof=1)) < 0.01
        True
        Display the histogram of the samples, along with
        the probability density function:
        >>> import matplotlib.pyplot as plt
        >>> count, bins, ignored = plt.hist(s, 30, density=True)
        >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
        ...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
        ...          linewidth=2, color='r')
        >>> plt.show()
        """
        cdef ndarray oloc, oscale
        cdef double floc, fscale
    
        oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED)
        oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED)
    
        if oloc.shape == oscale.shape == ():
            floc = PyFloat_AsDouble(loc)
            fscale = PyFloat_AsDouble(scale)
            if np.signbit(fscale):
                raise ValueError("scale < 0")
            return cont2_array_sc(self.internal_state, rk_normal, size, floc,
                                  fscale, self.lock)
    
        if np.any(np.signbit(oscale)):
            raise ValueError("scale < 0")
        return cont2_array(self.internal_state, rk_normal, size, oloc, oscale,
                           self.lock)
    

    duplicate question

    import numpy.random
    print(numpy.random.__file__)
    
    # /home/adam/.pyenv/versions/datasci/lib/python3.6/site-packages/numpy/random/__init__.py
    

    rk_gauss rk_normal

    double rk_normal(rk_state *state, double loc, double scale)
    {
        return loc + scale*rk_gauss(state);
    }
    

    Here here here