Python general function to realize array calculation

Time:2021-2-19

1、 Operation of array

Array operations can be added, subtracted, multiplied and divided. At the same time, these arithmetic operators can be arbitrarily combined to achieve the effect.

>>> x=np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> x=5
>>> x=np.arange(5)
>>> x+5
array([5, 6, 7, 8, 9])
>>> x-5
array([-5, -4, -3, -2, -1])
>>> x*2
array([0, 2, 4, 6, 8])
>>> x/2
array([0. , 0.5, 1. , 1.5, 2. ])
>>> x//2
array([0, 0, 1, 1, 2], dtype=int32)

2、 Operation of absolute value

There are three methods in total. The first method is to directly use ABS function which is not numpy library for calculation. The second and third methods are to use ABS function and absolute function of numpy library for calculation. As follows:

>>> x=np.array([1,2,3,-4,-5,-6])
>>> x
array([ 1,  2,  3, -4, -5, -6])
>>> abs(x)
array([1, 2, 3, 4, 5, 6])
>>> np.abs(x)
array([1, 2, 3, 4, 5, 6])
>>> np.absolute(x)
array([1, 2, 3, 4, 5, 6])

3、 The operation of trigonometric function

First, define an array object in NP of a, and then perform the operation

>>> a
array([0.        , 1.57079633, 3.14159265])
>>> np.sin(a)
array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])
>>> np.cos(a)
array([ 1.000000e+00,  6.123234e-17, -1.000000e+00])
>>> np.tan(a)
array([ 0.00000000e+00,  1.63312394e+16, -1.22464680e-16])

4、 Operation of exponent and logarithm

Operation of index:

>>> x=[1,2,3]
>>> x
[1, 2, 3]
>>> np.exp(x)
array([ 2.71828183,  7.3890561 , 20.08553692])
>>> np.exp2(x)
array([2., 4., 8.])
np.power(3,x)
array([ 3,  9, 27], dtype=int32)

Operation of logarithm:

>>> np.log(x)
array([0.        , 0.69314718, 1.09861229])
>>> np.log2(x)
array([0.       , 1.       , 1.5849625])
>>> x
[1, 2, 3]
>>> np.log10(x)
array([0.        , 0.30103   , 0.47712125])

Recommended Today

Background management system menu management module

1 menu management page design 1.1 business design Menu management, also known as resource management, is the external manifestation of system resources. This module is mainly to add, modify, query and delete the menu. CREATE TABLE `sys_menus` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Name ` varchar (50) default null comment ‘resource name’, `URL ` varchar […]