Python

您所在的位置:网站首页 python产生矩阵 Python

Python

#Python | 来源: 网络整理| 查看: 265

作为序列生成器,numpy.linspace()函数用于在线性空间中以均匀步长生成数字序列,返回array;numpy.arange()函数用于生成固定步长的数字序列,返回array;range() 函数与arange()类似,但返回int类型list,不在numpy模块下,与list()同时使用;reshape()函数将一维数组转化为多维数组,不可用于list。 1、numpy.linspace()函数 结构:numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 其中: start:数字的起始值 stop:数字的末尾值 num:生成的数字数量,默认为50 endpoint:若为True(默认取值),结果包含末尾值;若为False,结果不包含末尾值,步长也会发生变化 retstep:若为True,结果包含样本步长;若为False(默认取值),结果不包含样本步长 dtype:确定数据类型,若未限制,那么从其他输入参数推断其类型。 举例:

> x=np.linspace(1,2,5) array([1. , 1.25, 1.5 , 1.75, 2. ]) > x=np.linspace(1,2,5,endpoint=False) array([1. , 1.2, 1.4, 1.6, 1.8]) > x=np.linspace(1,2,5,retstep=True) (array([1. , 1.25, 1.5 , 1.75, 2. ]), 0.25) > x=np.linspace(1,2,5,retstep=False) array([1. , 1.25, 1.5 , 1.75, 2. ]) > x=np.linspace(1,4,5,dtype='int') array([1, 1, 2, 3, 4]) import numpy as np from matplotlib import pyplot as plt x=np.linspace(1,2,8) y=2*x+1 plt.figure() plt.plot(x,y,'o')

2、numpy.arange()函数 arange(start, end, step),以start开始,以stop终止,不包含末尾值,步长为step,默认步长为1。可以使用float型数据。 当未指定start及stop时,以固定步长1生成以0开头的若干个数字。

> x=np.arange(1,10,2) array([1, 3, 5, 7, 9]) > x=np.arange(1,10) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) > x=np.arange(5) array([0, 1, 2, 3, 4]) > x=np.arange(1.2,3) array([1.2, 2.2]) > x=np.arange(1.2,3,0.5) array([1.2, 1.7, 2.2, 2.7])

3、range()函数 range(start, end, step),返回一个list对象,起始值为start,终止值为end,但不含终止值,步长为step。只能创建int型list。

> x=list(range(1,10)) [1, 2, 3, 4, 5, 6, 7, 8, 9] > x=list(range(1,10,2)) [1, 3, 5, 7, 9] > x=list(range(1.0,10,2)) #不支持float类型 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 x=list(range(1.0,10,2)) 2 x TypeError: 'float' object cannot be interpreted as an integer

4、reshape()函数 reshape()函数将一维数组转化为多维数组

#二维数组 > x=np.arange(8).reshape(2,4) array([[0, 1, 2, 3], [4, 5, 6, 7]]) #三维数组 > x=np.arange(6).reshape(3,2) array([[0, 1], [2, 3], [4, 5]]) > x=np.linspace(1,2,8).reshape(2,4) array([[1. , 1.14285714, 1.28571429, 1.42857143], [1.57142857, 1.71428571, 1.85714286, 2. ]])


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3