numpy


Numpy

NumPy jest podstawowym pakiet (dodatkowym) w Pythonie do obliczeń naukowych. Integruje on niskopoziomowe biblioteki takie jak BLAS i LAPACK lub ATLAS. Podstawowe właściwości NumPy to :

  • potężny N-wymiarowy obiekt tablicy danych
  • rozbudowane funkcje
  • narzędzia do integracji z kodem napisanym w C/C++ i Fortranie
  • narzędzia do algebry liniowej, transformaty Fouriera czy generator liczb losowych

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.

Import


In [2]:
import numpy as np

Functions

  • np.abs()
  • np.sign()
  • np.sqrt()

Exponents and logarithms

  • np.log()
  • np.log10()
  • np.exp()

Trigonometric functions

  • np.sin()
  • np.cos()
  • np.tan()
  • np.arcsin()
  • np.arccos()
  • np.arctan()

Hiperbolic functions

  • np.sinh()
  • np.cosh()
  • np.tanh()
  • np.arcsinh()
  • np.arccosh()
  • np.arctanh()

In [ ]:

Random numbers

Mersenne Twister algorithm for pseudorandom number generation

Seed the generator


In [3]:
np.random.seed(293423)
np.random.rand(5)


Out[3]:
array([0.33677247, 0.52693437, 0.79529578, 0.78867702, 0.02147624])

In [3]:
np.random.rand(5)


Out[3]:
array([0.84612516, 0.0704939 , 0.1526965 , 0.77831701, 0.80821151])

Random values in a given shape

Random samples from a uniform distribution over [0, 1)


In [4]:
np.random.rand(2,3)


Out[4]:
array([[0.84612516, 0.0704939 , 0.1526965 ],
       [0.77831701, 0.80821151, 0.82198398]])

In [9]:
np.random.rand(8).reshape((4,2))


Out[9]:
array([[0.5219473 , 0.11240232],
       [0.65049125, 0.67164447],
       [0.3756778 , 0.09623913],
       [0.88756776, 0.33254026]])

Random integers from low (inclusive) to high (exclusive)


In [6]:
np.random.randint(5, 10)


Out[6]:
6

Random numbers from distributions

Draw samples from a Poisson distribution

Poisson distribution with lambda = 6.0


In [176]:
np.random.seed(100)
np.random.poisson(6.0)


Out[176]:
4

In [8]:
np.random.seed(100)
np.random.poisson([6.0, 1.0])


Out[8]:
array([4, 0])

Draw random samples from a normal (Gaussian) distribution

Continuous normal (Gaussian) distribution with mean micro=1.5 and standard deviation sigma=4.0:


In [9]:
np.random.normal(1.5, 4.)


Out[9]:
5.425283147804926

Continuous normal (Gaussian) distribution with mean micro=0.0 and standard deviation sigma=1.0:


In [10]:
np.random.normal()


Out[10]:
0.5142188413943821

In [11]:
np.random.normal(size=5)


Out[11]:
array([ 0.22117967, -1.07004333, -0.18949583,  0.25500144, -0.45802699])

Modify a sequence in-place by shuffling its contents


In [12]:
arr = np.arange(10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

np.random.shuffle(arr)

In [13]:
arr


Out[13]:
array([0, 2, 1, 6, 9, 8, 7, 4, 3, 5])

Multi-dimensional arrays are only shuffled along the first axis:


In [10]:
arr = np.arange(9).reshape((3, 3))
arr


Out[10]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [11]:
np.random.shuffle(arr)
arr


Out[11]:
array([[6, 7, 8],
       [3, 4, 5],
       [0, 1, 2]])

Polynomials

Defining polynomial

$$Ax^3 + Bx^2 + Cx + D$$

In [13]:
np.poly([-1, 1, 10])


Out[13]:
array([  1., -10.,  -1.,  10.])

Calculating roots of a polynomial


In [15]:
np.roots([1., -10., -1., 10.])


Out[15]:
array([10., -1.,  1.])

Evaluate a polynomial at specific values


In [18]:
np.polyval([1, -10, -1, 10], 10)


Out[18]:
0

Antiderivative (indefinite integral) of a polynomial


In [19]:
np.polyder([1./4., 1./3., 1./2., 1., 0.])


Out[19]:
array([1., 1., 1., 1.])

Derivatives


In [20]:
np.polyint([1, 1, 1, 1])


Out[20]:
array([0.25      , 0.33333333, 0.5       , 1.        , 0.        ])

Least squares polynomial fit


In [21]:
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [0, 2, 1, 3, 7, 10, 11, 19]

np.polyfit(x, y, 2)


Out[21]:
array([ 0.375     , -0.88690476,  1.05357143])

Polynomial Arithmetic

  • np.polyadd()
  • np.polysub()
  • np.polymul()
  • np.polydiv()

In [22]:
np.polyadd([1, 2], [9, 5, 4])


Out[22]:
array([9, 6, 6])

Arrays

Create array

From list:


In [23]:
np.array([1, 2, 3])


Out[23]:
array([1, 2, 3])

In [24]:
np.array([1, 4, 5, 8], float)


Out[24]:
array([1., 4., 5., 8.])

From list of lists:


In [25]:
np.array([[1,2], [3,4]])


Out[25]:
array([[1, 2],
       [3, 4]])

Generating arrays


In [26]:
np.arange(3)


Out[26]:
array([0, 1, 2])

In [27]:
np.arange(3.)


Out[27]:
array([0., 1., 2.])

In [28]:
np.arange(3, 7)


Out[28]:
array([3, 4, 5, 6])

In [29]:
np.arange(3, 12, step=2)


Out[29]:
array([ 3,  5,  7,  9, 11])

In [30]:
np.arange(start=3, stop=12, step=2, dtype=float)


Out[30]:
array([ 3.,  5.,  7.,  9., 11.])

Slicing arrays


In [17]:
a = np.array([1, 4, 5, 8], float)
a


Out[17]:
array([1., 4., 5., 8.])

In [32]:
a[:2]


Out[32]:
array([1., 4.])

In [35]:
a = np.array([[1, 2, 3], [4, 5, 6]], float)
a


Out[35]:
array([[1., 2., 3.],
       [4., 5., 6.]])

In [33]:
a[3]


Out[33]:
8.0

In [34]:
a[0] = 5
a


Out[34]:
array([5., 4., 5., 8.])

In [36]:
a[0][0]
a[0,0]


Out[36]:
1.0

In [37]:
a[0]


Out[37]:
array([1., 2., 3.])

In [38]:
a[1,:]


Out[38]:
array([4., 5., 6.])

In [39]:
a[-1,-2]


Out[39]:
5.0

In [40]:
a[-1,-2:]


Out[40]:
array([5., 6.])

In [41]:
a[-1:,-2:]


Out[41]:
array([[5., 6.]])

Array shape


In [18]:
a = np.array([[1, 2, 3], [4, 5, 6]], float)
a


Out[18]:
array([[1., 2., 3.],
       [4., 5., 6.]])

In [43]:
len(a)


Out[43]:
2

In [44]:
a.shape


Out[44]:
(2, 3)

In [19]:
a.dtype


Out[19]:
dtype('float64')

In [24]:
a.astype(int)
a.dtype


Out[24]:
dtype('int64')

In [23]:
a = a.astype(int)
a.dtype


Out[23]:
dtype('int64')

In [48]:
6 in a


Out[48]:
True

In [49]:
0 in a


Out[49]:
False

In [25]:
a = np.array(range(10), float)

In [26]:
a = a.reshape((5, 2))
a


Out[26]:
array([[0., 1.],
       [2., 3.],
       [4., 5.],
       [6., 7.],
       [8., 9.]])

In [27]:
a.reshape((2, 5))


Out[27]:
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])

In [28]:
a


Out[28]:
array([[0., 1.],
       [2., 3.],
       [4., 5.],
       [6., 7.],
       [8., 9.]])

In [54]:
a = np.array([1, 2, 3], float)

In [55]:
b = a
c = a.copy()

In [56]:
a[0] = 0

In [57]:
b


Out[57]:
array([0., 2., 3.])

In [58]:
c


Out[58]:
array([1., 2., 3.])

In [59]:
a = np.array([[1, 2], [3, 4]], float)
a.tolist()


Out[59]:
[[1.0, 2.0], [3.0, 4.0]]

In [60]:
list(a)


Out[60]:
[array([1., 2.]), array([3., 4.])]

In [61]:
a = np.array([1, 2, 3], float)

In [62]:
s = a.tostring()
s


Out[62]:
b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@'

In [63]:
np.frombuffer(s)


Out[63]:
array([1., 2., 3.])

Array Data


In [183]:
n1 = np.array([1,2,3])
n2 = np.array([[1,2],[3,4]])

print(f'Wymiar: n1: {n1.ndim}, n2: {n2.ndim}')

print(f'Kształt: n1: {n1.shape}, n2: {n2.shape}')

print(f'Rozmiar: n1: {n1.size}, n2: {n2.size}')

print(f'Typ: n1: {n1.dtype}, n2: {n2.dtype}')

print(f'Rozmiar elementu (w bajtach): n1: {n1.itemsize}, n2: {n2.itemsize}')

print(f'Wskaźnik do danych: n1: {n1.data}, n2: {n2.data}')


Wymiar: n1: 1, n2: 2
Kształt: n1: (3,), n2: (2, 2)
Rozmiar: n1: 3, n2: 4
Typ: n1: int64, n2: int64
Rozmiar elementu (w bajtach): n1: 8, n2: 8
Wskaźnik do danych: n1: <memory at 0x117c49ac8>, n2: <memory at 0x117de8048>

W przeciwieństwie do kolekcji, tablice mogą mieć tylko jeden typ elementu, choć może być złożony

https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html


In [184]:
for v in [1, 1., 1j]:
    a = np.array([v])
    print('Tablica: {}, typ: {}'.format(a, a.dtype))


Tablica: [1], typ: int64
Tablica: [1.], typ: float64
Tablica: [0.+1.j], typ: complex128

Array modification


In [64]:
a = np.arange(3)
a


Out[64]:
array([0, 1, 2])

In [65]:
a.fill(0)
a


Out[65]:
array([0, 0, 0])

In [178]:
a = np.array(range(6), float).reshape((2, 3))
a


Out[178]:
array([[0., 1., 2.],
       [3., 4., 5.]])

In [179]:
a.transpose()


Out[179]:
array([[0., 3.],
       [1., 4.],
       [2., 5.]])

In [180]:
a.T


Out[180]:
array([[0., 3.],
       [1., 4.],
       [2., 5.]])

In [68]:
a = np.array([[1, 2, 3], [4, 5, 6]], float)
a


Out[68]:
array([[1., 2., 3.],
       [4., 5., 6.]])

In [69]:
a.flatten()


Out[69]:
array([1., 2., 3., 4., 5., 6.])

In [70]:
a = np.array(range(6), float).reshape((2, 3, 1))
a


Out[70]:
array([[[0.],
        [1.],
        [2.]],

       [[3.],
        [4.],
        [5.]]])

In [71]:
a.squeeze()


Out[71]:
array([[0., 1., 2.],
       [3., 4., 5.]])

Math operations


In [72]:
a = np.array([1,2,3], float)
b = np.array([5,2,6], float)

In [73]:
a + b


Out[73]:
array([6., 4., 9.])

In [74]:
a - b


Out[74]:
array([-4.,  0., -3.])

In [75]:
a * b


Out[75]:
array([ 5.,  4., 18.])

In [76]:
b / a


Out[76]:
array([5., 1., 2.])

In [77]:
a % b


Out[77]:
array([1., 0., 3.])

In [78]:
b ** a


Out[78]:
array([  5.,   4., 216.])

In [79]:
a = np.array([[1,2], [3,4]], float)
b = np.array([[2,0], [1,3]], float)

In [80]:
a * b


Out[80]:
array([[ 2.,  0.],
       [ 3., 12.]])

Array concatenation


In [181]:
a = np.array([1,2], float)
b = np.array([3,4,5,6], float)
c = np.array([7,8,9], float)

np.concatenate((a, b, c))


Out[181]:
array([1., 2., 3., 4., 5., 6., 7., 8., 9.])

Array multiplication


In [81]:
a = np.array([[1, 0], [0, 1]])
b = np.array([[4, 1], [2, 2]])

a @ b


Out[81]:
array([[4, 1],
       [2, 2]])

In [82]:
a = np.array([[1, 0], [0, 1]])
b = np.array([[4, 1], [2, 2]])

a * b


Out[82]:
array([[4, 0],
       [0, 2]])

Shape operations


In [31]:
a = np.array([[1, 2], [3, 4], [5, 6]], float)
a


Out[31]:
array([[1., 2.],
       [3., 4.],
       [5., 6.]])

In [32]:
b = np.array([-1, 3], float)
b


Out[32]:
array([-1.,  3.])

In [33]:
a + b


Out[33]:
array([[0., 5.],
       [2., 7.],
       [4., 9.]])

In [34]:
a = np.zeros((2,2), float)
a


Out[34]:
array([[0., 0.],
       [0., 0.]])

In [35]:
b = np.array([-1., 3.], float)
b


Out[35]:
array([-1.,  3.])

In [36]:
a + b


Out[36]:
array([[-1.,  3.],
       [-1.,  3.]])

In [38]:
a + b [np.newaxis, :]


Out[38]:
array([[-1.,  3.],
       [-1.,  3.]])

In [90]:
a + b [:, np.newaxis]


Out[90]:
array([[-1., -1.],
       [ 3.,  3.]])

Other operations


In [91]:
a = np.array([1.1, 1.5, 1.9], float)

In [92]:
np.sqrt(a)


Out[92]:
array([1.04880885, 1.22474487, 1.37840488])

In [93]:
np.floor(a)


Out[93]:
array([1., 1., 1.])

In [94]:
np.ceil(a)


Out[94]:
array([2., 2., 2.])

In [95]:
np.rint(a)


Out[95]:
array([1., 2., 2.])

In [96]:
np.pi


Out[96]:
3.141592653589793

In [97]:
np.e


Out[97]:
2.718281828459045

In [98]:
np.nan


Out[98]:
nan

In [99]:
np.inf


Out[99]:
inf

Array iteriation


In [100]:
a = np.array([1, 4, 5], int)

for x in a:
    print(x)


1
4
5

In [41]:
a = np.array([[1, 2], [3, 4], [5, 6]], float)

for x in a:
    print(x)


[1. 2.]
[3. 4.]
[5. 6.]

Array operations


In [102]:
a = np.array([2, 4, 3], float)
a


Out[102]:
array([2., 4., 3.])

In [103]:
a.sum()


Out[103]:
9.0

In [104]:
a.prod()


Out[104]:
24.0

In [105]:
a = np.array([2, 1, 9], float)
a


Out[105]:
array([2., 1., 9.])

In [106]:
a.mean()


Out[106]:
4.0

In [107]:
a.var()


Out[107]:
12.666666666666666

In [108]:
a.std()


Out[108]:
3.559026084010437

In [109]:
a.min()


Out[109]:
1.0

In [110]:
a.max()


Out[110]:
9.0

In [111]:
a.argmin()


Out[111]:
1

In [112]:
a.argmax()


Out[112]:
2

In [113]:
a = np.array([6, 2, 5, -1, 0], float)
sorted(a)


Out[113]:
[-1.0, 0.0, 2.0, 5.0, 6.0]

In [114]:
a.sort()
a


Out[114]:
array([-1.,  0.,  2.,  5.,  6.])

In [115]:
a = np.array([6, 2, 5, -1, 0], float)

a.clip(0, 5)


Out[115]:
array([5., 2., 5., 0., 0.])

In [116]:
a = np.array([1, 1, 4, 5, 5, 5, 7], float)

np.unique(a)


Out[116]:
array([1., 4., 5., 7.])

In [117]:
a = np.array([[1, 2], [3, 4]], float)

a.diagonal()


Out[117]:
array([1., 4.])

Comparison operators


In [118]:
a = np.array([1, 3, 0], float)
b = np.array([0, 3, 2], float)

In [119]:
a > b


Out[119]:
array([ True, False, False])

In [120]:
a == b


Out[120]:
array([False,  True, False])

In [121]:
a <= b


Out[121]:
array([False,  True,  True])

In [122]:
c = a > b
c


Out[122]:
array([ True, False, False])

In [123]:
any(c)


Out[123]:
True

In [124]:
all(c)


Out[124]:
False

In [44]:
a = np.array([1, 3, 0], float)

np.logical_and(a > 0, a < 3)


Out[44]:
array([ True, False, False])

In [126]:
a = np.array([True, False, True], bool)

np.logical_not(a)


Out[126]:
array([False,  True, False])

In [127]:
a = np.array([True, False, True], bool)
b = np.array([False, True, False], bool)

np.logical_or(a, b)


Out[127]:
array([ True,  True,  True])

Where


In [45]:
a = np.array([1, 3, 0], float)

np.where(a != 0)


Out[45]:
(array([0, 1]),)

In [129]:
b = np.array([1, 0, 3, 4, 0], float)

np.where(b != 0)


Out[129]:
(array([0, 2, 3]),)

In [130]:
a = np.array([1, 3, 0], float)

np.where(a != 0, a, None)  # for element ``a != 0`` return such element, otherwise ``None``


Out[130]:
array([1.0, 3.0, None], dtype=object)

In [131]:
a = np.array([1, 3, 0], float)

np.where(a != 0, a ** 2, a)


Out[131]:
array([1., 9., 0.])

In [132]:
np.where(a != 0, a ** 2, 10)


Out[132]:
array([ 1.,  9., 10.])

Nonzero


In [133]:
a = np.array([[0, 1], [3, 0]], float)
a.nonzero()


Out[133]:
(array([0, 1]), array([1, 0]))

IsFinite and IsNaN


In [134]:
a = np.array([1, np.NaN, np.Inf], float)

In [135]:
np.isnan(a)


Out[135]:
array([False,  True, False])

In [136]:
np.isfinite(a)


Out[136]:
array([ True, False, False])

Array item selection and manipulation


In [46]:
a = np.array([[6, 4], [5, 9]], float)
a


Out[46]:
array([[6., 4.],
       [5., 9.]])

In [138]:
a >= 6


Out[138]:
array([[ True, False],
       [False,  True]])

In [139]:
a[a >= 6]


Out[139]:
array([6., 9.])

In [140]:
a[np.logical_and(a > 5, a < 9)]


Out[140]:
array([6.])

In [47]:
a = np.array([2, 4, 6, 8], float)
b = np.array([0, 0, 1, 3, 2, 1], int)
a[b]


Out[47]:
array([2., 2., 4., 8., 6., 4.])

In [142]:
a = np.array([2, 4, 6, 8], float)

a[[0, 0, 1, 3, 2, 1]]


Out[142]:
array([2., 2., 4., 8., 6., 4.])

In [52]:
a = np.array([[1, 4], [9, 16]], float)
b = np.array([0, 0, 1, 1, 0], int)
c = np.array([0, 1, 1, 1, 1], int)

a[b,c]


Out[52]:
array([ 1.,  4., 16., 16.,  4.])

In [144]:
a = np.array([2, 4, 6, 8], float)
b = np.array([0, 0, 1, 3, 2, 1], int)

a.take(b)


Out[144]:
array([2., 2., 4., 8., 6., 4.])

In [145]:
a = np.array([[0, 1], [2, 3]], float)
b = np.array([0, 0, 1], int)

a.take(b, axis=0)


Out[145]:
array([[0., 1.],
       [0., 1.],
       [2., 3.]])

In [146]:
a.take(b, axis=1)


Out[146]:
array([[0., 0., 1.],
       [2., 2., 3.]])

In [147]:
a = np.array([0, 1, 2, 3, 4, 5], float)
b = np.array([9, 8, 7], float)

a.put([0, 3], b)
a


Out[147]:
array([9., 1., 2., 8., 4., 5.])

In [148]:
a = np.array([0, 1, 2, 3, 4, 5], float)

a.put([0, 3], 5)
a


Out[148]:
array([5., 1., 2., 5., 4., 5.])

Statistics

Compute the median along the specified axis


In [149]:
a = np.array([1, 4, 3, 8, 9, 2, 3], float)

np.median(a)


Out[149]:
3.0

Estimate a covariance matrix


In [150]:
a = np.array([[1, 2, 1, 3], [5, 3, 1, 8]], float)

np.cov(a)


Out[150]:
array([[0.91666667, 2.08333333],
       [2.08333333, 8.91666667]])

In [151]:
np.cov(a, ddof=0)


Out[151]:
array([[0.6875, 1.5625],
       [1.5625, 6.6875]])

Pearson product-moment correlation coefficients


In [152]:
a = np.array([[1, 2, 1, 3], [5, 3, 1, 8]], float)

np.corrcoef(a)


Out[152]:
array([[1.        , 0.72870505],
       [0.72870505, 1.        ]])

Vector and matrix mathematics


In [153]:
a = np.array([[0, 1], [2, 3]], float)
b = np.array([2, 3], float)
c = np.array([[1, 1], [4, 0]], float)

In [154]:
np.dot(b, a)


Out[154]:
array([ 6., 11.])

In [155]:
np.dot(a, b)


Out[155]:
array([ 3., 13.])

In [156]:
np.dot(a, c)


Out[156]:
array([[ 4.,  0.],
       [14.,  2.]])

In [157]:
np.dot(c, a)


Out[157]:
array([[2., 4.],
       [0., 4.]])

In [158]:
a = np.array([1, 4, 0], float)
b = np.array([2, 2, 1], float)

In [159]:
np.outer(a, b)


Out[159]:
array([[2., 2., 1.],
       [8., 8., 4.],
       [0., 0., 0.]])

In [160]:
np.inner(a, b)


Out[160]:
10.0

In [161]:
np.cross(a, b)


Out[161]:
array([ 4., -1., -6.])

Linear algebra


In [162]:
a = np.array([[4, 2, 0], [9, 3, 7], [1, 2, 1]], float)

np.linalg.det(a)


Out[162]:
-48.00000000000003

In [163]:
a = np.array([[4, 2, 0], [9, 3, 7], [1, 2, 1]], float)

vals, vecs = np.linalg.eig(a)

In [164]:
vals


Out[164]:
array([ 8.85591316,  1.9391628 , -2.79507597])

In [165]:
vecs


Out[165]:
array([[-0.3663565 , -0.54736745,  0.25928158],
       [-0.88949768,  0.5640176 , -0.88091903],
       [-0.27308752,  0.61828231,  0.39592263]])

In [166]:
a = np.array([[4, 2, 0], [9, 3, 7], [1, 2, 1]], float)
b = np.linalg.inv(a)
b


Out[166]:
array([[ 0.22916667,  0.04166667, -0.29166667],
       [ 0.04166667, -0.08333333,  0.58333333],
       [-0.3125    ,  0.125     ,  0.125     ]])

In [167]:
np.dot(a, b)


Out[167]:
array([[1.00000000e+00, 5.55111512e-17, 0.00000000e+00],
       [0.00000000e+00, 1.00000000e+00, 2.22044605e-16],
       [0.00000000e+00, 1.38777878e-17, 1.00000000e+00]])

Matrix

Numpy ma również typ macierzy matrix. Jest on bardzo podobny do tablicy ale podstawowe operacje wykonywane są w sposób macierzowy a nie tablicowy.


In [168]:
a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

In [169]:
a * b


Out[169]:
matrix([[19, 22],
        [43, 50]])

In [170]:
a @ b


Out[170]:
matrix([[19, 22],
        [43, 50]])

In [171]:
a ** 2


Out[171]:
matrix([[ 7, 10],
        [15, 22]])

In [173]:
a * 2


Out[173]:
matrix([[2, 4],
        [6, 8]])

In [185]:
a = np.diag([3,4])
a


Out[185]:
array([[3, 0],
       [0, 4]])

Linear Algebra


In [187]:
a = np.matrix([[1,2], [3,4]])
print('det(a) = {}'.format(np.linalg.det(a)))


det(a) = -2.0000000000000004

Linear algebra basics

Function Description
norm Vector or matrix norm
inv Inverse of a square matrix
solve Solve a linear system of equations
det Determinant of a square matrix
slogdet Logarithm of the determinant of a square matrix
lstsq Solve linear least-squares problem
pinv Pseudo-inverse (Moore-Penrose) calculated using a singular value decomposition
matrix_power Integer power of a square matrix
matrix_rank Calculate matrix rank using an SVD-based method

Eigenvalues and decompositions

Function Description
eig Eigenvalues and vectors of a square matrix
eigh Eigenvalues and eigenvectors of a Hermitian matrix
eigvals Eigenvalues of a square matrix
eigvalsh Eigenvalues of a Hermitian matrix
qr QR decomposition of a matrix
svd Singular value decomposition of a matrix
cholesky Cholesky decomposition of a matrix

Tensor operations

Function Description
tensorsolve Solve a linear tensor equation
tensorinv Calculate an inverse of a tensor

Exceptions

Function Description
LinAlgError Indicates a failed linear algebra operation

Assignments

Matrix multiplication

  • Używając numpy oraz operatora @ oraz *
  • Czym się różnią?
def matrix_multiplication(A, B):
    """
    >>> import numpy as np

    >>> A = np.array([[1, 0], [0, 1]])
    >>> B = [[4, 1], [2, 2]]
    >>> matrix_multiplication(A, B)
    [[4, 1], [2, 2]]

    >>> A = [[1,0,1,0], [0,1,1,0], [3,2,1,0], [4,1,2,0]]
    >>> B = np.matrix([[4,1], [2,2], [5,1], [2,3]])
    >>> matrix_multiplication(A, B)
    [[9, 2], [7, 3], [21, 8], [28, 8]]
    """
    pass

About

  • Filename: numpy-matrix-mul.py
  • Lines of code to write: 2 lines
  • Estimated time of completion: 5 min

Sum of inner matrix

  • Wygeneruj macierz (16x16) randomowych intów o wartościach od 10 do 100
  • Przekonwertuj macierz na typ float
  • Transponuj ją
  • Policz sumę środkowych (4x4) elementów macierzy
  • Wyświetl wartość (skalar) sumy, a nie nie wektor

About

  • Filename: numpy-sum.py
  • Lines of code to write: 4 lines
  • Estimated time of completion: 5 min

Szukanie liczby

  • Mamy liczbę trzycyfrową.
  • Jeżeli od liczny dziesiątek odejmiemy liczbę jedności otrzymamy 6.
  • Jeżeli do liczby dziesiątek dodamy liczbę jedności otrzymamy 10.
  • Znajdź wszystkie liczby trzycyfrowe spełniające ten warunek
  • Znajdź liczby trzycyfrowe podzielne przez 3

Hints

  • Ax=B
  • x=A−1B
liczba_dziesiatek - liczba_jednosci = 6
liczba_dziesiatek + liczba_jednosci = 10

liczba_dziesiatek = liczba_jednosci + 6
liczba_dziesiatek + liczba_jednosci = 10

liczba_dziesiatek = liczba_jednosci + 6
(liczba_jednosci + 6) + liczba_jednosci 10

liczba_dziesiatek = liczba_jednosci + 6
2 * liczba_jednosci + 6 = 10

liczba_dziesiatek = liczba_jednosci + 6
liczba_jednosci = 8 / 2

liczba_dziesiatek = 2 + 6
liczba_jednosci = 2

liczba_dziesiatek = 8
liczba_jednosci = 2
x1 - x2 = 6
x1 + x2 = 10

x1 = 6 + x2
6 + x2 + x2 = 10

2 * x2 = 4
x2 = 2
x1 = 8
import numpy as np

A = np.matrix([[1, -1], [1, 1]])
# matrix([[ 1, -1],
#        [ 1,  1]])

B = np.matrix([6, 10]).T  # Transpose matrix
# matrix([[ 6],
#        [10]])

x = A**(-1) * B
# matrix([[8.],
#        [2.]])

A*x == B
# matrix([[ True],
#        [ True]])

res1 = np.arange(1, 10)*100 + 10*x[0,0] + 1*x[1,0]
# array([182., 282., 382., 482., 582., 682., 782., 882., 982.])

res1[res1 % 3 == 0]
# array([282., 582., 882.])

m = res1 % 3 == 0
# array([False,  True, False, False,  True, False, False,  True, False])

res1[m]
# array([282., 582., 882.])

res2 = res1[m]
# array([282., 582., 882.])

In [ ]: