鱼C论坛

 找回密码
 立即注册
查看: 1714|回复: 2

[技术交流] 关于np.linspace函数

[复制链接]
发表于 2021-1-18 17:16:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Python初学者8号 于 2021-1-18 17:17 编辑

正在学习matplotlib包
我遇到了linspace函数,我来研就一下他的作用。

这是函数的源文档:
Help on function linspace in module numpy:

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
    Return evenly spaced numbers over a specified interval.
   
    Returns `num` evenly spaced samples, calculated over the
    interval [`start`, `stop`].
   
    The endpoint of the interval can optionally be excluded.
   
    .. versionchanged:: 1.16.0
        Non-scalar `start` and `stop` are now supported.
   
    Parameters
    ----------
    start : array_like
        The starting value of the sequence.
    stop : array_like
        The end value of the sequence, unless `endpoint` is set to False.
        In that case, the sequence consists of all but the last of ``num + 1``
        evenly spaced samples, so that `stop` is excluded.  Note that the step
        size changes when `endpoint` is False.
    num : int, optional
        Number of samples to generate. Default is 50. Must be non-negative.
    endpoint : bool, optional
        If True, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    retstep : bool, optional
        If True, return (`samples`, `step`), where `step` is the spacing
        between samples.
    dtype : dtype, optional
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.
   
        .. versionadded:: 1.9.0
   
    axis : int, optional
        The axis in the result to store the samples.  Relevant only if start
        or stop are array-like.  By default (0), the samples will be along a
        new axis inserted at the beginning. Use -1 to get an axis at the end.
   
        .. versionadded:: 1.16.0
   
    Returns
    -------
    samples : ndarray
        There are `num` equally spaced samples in the closed interval
        ``[start, stop]`` or the half-open interval ``[start, stop)``
        (depending on whether `endpoint` is True or False).
    step : float, optional
        Only returned if `retstep` is True
   
        Size of spacing between samples.
   
   
    See Also
    --------
    arange : Similar to `linspace`, but uses a step size (instead of the
             number of samples).
    geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
                scale (a geometric progression).
    logspace : Similar to `geomspace`, but with the end points specified as
               logarithms.
   
    Examples
    --------
    >>> np.linspace(2.0, 3.0, num=5)
    array([2.  , 2.25, 2.5 , 2.75, 3.  ])
    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
    array([2. ,  2.2,  2.4,  2.6,  2.8])
    >>> np.linspace(2.0, 3.0, num=5, retstep=True)
    (array([2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)



    Graphical illustration:
   
    >>> import matplotlib.pyplot as plt
    >>> N = 8
    >>> y = np.zeros(N)
    >>> x1 = np.linspace(0, 10, N, endpoint=True)
    >>> x2 = np.linspace(0, 10, N, endpoint=False)
    >>> plt.plot(x1, y, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.plot(x2, y + 0.5, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.ylim([-0.5, 1])
    (-0.5, 1)
    >>> plt.show()



刚开始不是很懂num参数和endpoint概念,以及说明文档中的这句话

The end value of the sequence, unless `endpoint` is set to False.
        In that case, the sequence consists of all but the last of ``num + 1``
        evenly spaced samples, so that `stop` is excluded.  Note that the step
        size changes when `endpoint` is False.


这样理解这个参数,也是引用他们自己写的例子,我加了一点
  1.     Examples
  2.     --------
  3.     >>> np.linspace(2.0, 3.0, num=5)
  4.     array([2.  , 2.25, 2.5 , 2.75, 3.  ])
  5.     >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
  6.     array([2. ,  2.2,  2.4,  2.6,  2.8])
  7.     >>> np.linspace(2.0, 3.0, num=5, retstep=True)
  8.     (array([2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)
  9.     #我加的:
  10.      >>>np.linspace(2.0, 3.0, num=6, endpoint=True)
  11.      >>>array([2. , 2.2, 2.4, 2.6, 2.8, 3. ])
复制代码


所以作用就是增加num为num+1,然后删除最后一个数,然后输出num个数字,哈哈
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-1-18 18:20:18 | 显示全部楼层
  1. linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
复制代码


好了,现在说说retstep参数:
首先看看doc的解释:
    retstep : bool, optional
        If True, return (`samples`, `step`), where `step` is the spacing
        between samples.

所以,从名字来说,它是return  step的缩写,作用来说 ,看下面:
  1. >>> c= np.linspace(1, 3, num=3, endpoint=True, retstep=True, dtype=None, axis=0)
  2. >>> c
  3. (array([1., 2., 3.]), 1.0)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-18 18:36:05 | 显示全部楼层
哈哈,通过这个 命令找到了源代码了 哈哈
  1. import numpy as np
  2. import inspect
  3. print(inspect.getsource(np.linspace))
复制代码




                               
登录/注册后可看大图


以下就是源代码

  1. num = operator.index(num)
  2.     if num < 0:
  3.         raise ValueError("Number of samples, %s, must be non-negative." % num)
  4.     div = (num - 1) if endpoint else num

  5.     # Convert float/complex array scalars to float, gh-3504
  6.     # and make sure one can use variables that have an __array_interface__, gh-6634
  7.     start = asanyarray(start) * 1.0
  8.     stop  = asanyarray(stop)  * 1.0

  9.     dt = result_type(start, stop, float(num))
  10.     if dtype is None:
  11.         dtype = dt

  12.     delta = stop - start
  13.     y = _nx.arange(0, num, dtype=dt).reshape((-1,) + (1,) * ndim(delta))
  14.     # In-place multiplication y *= delta/div is faster, but prevents the multiplicant
  15.     # from overriding what class is produced, and thus prevents, e.g. use of Quantities,
  16.     # see gh-7142. Hence, we multiply in place only for standard scalar types.
  17.     _mult_inplace = _nx.isscalar(delta)
  18.     if div > 0:
  19.         step = delta / div
  20.         if _nx.any(step == 0):
  21.             # Special handling for denormal numbers, gh-5437
  22.             y /= div
  23.             if _mult_inplace:
  24.                 y *= delta
  25.             else:
  26.                 y = y * delta
  27.         else:
  28.             if _mult_inplace:
  29.                 y *= step
  30.             else:
  31.                 y = y * step
  32.     else:
  33.         # sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
  34.         # have an undefined step
  35.         step = NaN
  36.         # Multiply with delta to allow possible override of output class.
  37.         y = y * delta

  38.     y += start

  39.     if endpoint and num > 1:
  40.         y[-1] = stop

  41.     if axis != 0:
  42.         y = _nx.moveaxis(y, 0, axis)

  43.     if retstep:
  44.         return y.astype(dtype, copy=False), step
  45.     else:
  46.         return y.astype(dtype, copy=False)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 22:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表