Get the App
SLTechnology News&Howtos  ›  Development  › 

Which is more efficient to add vectors in Python or numpy?

Shulou Source: shulou.com Published: 2022-06-03 18:29:45 10月03日 Update

This article mainly explains the "Python and numpy vector addition which is more efficient", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Python and numpy vector addition which is more efficient" bar!

Directly use Python to add vectors.

#-*-coding:utf-8-*-# vector addition def pythonsum (n): a = range (n) b = range (n) c = [] for i in range (len (a)): a [I] = iDefinite2b [I] = iLife3 c.append (a [I] + b [I]) return a, type (pythonsum (4)) for arg in pythonsum (4): print arg

From this output, we can see that when return has multiple values, it is returned in the form of a list.

([0,1,4,9], [0,1,8,27], [0,2,12,36]) [0,1,4,9] [0,1,8,27] [0,2,12,36]

Using numpy package to realize the addition of two vectors

Def numpysum (n): a = np.arange (n) * * 2b = np.arange (n) * * 3c = a + b return an array ([0,1,4,9]), array ([0,1,8,27]), array ([0,2,12,36]) [0149] [01827] [021236]

Compare the addition of two vectors with Python and the addition of two vectors with numpy

Size = 1000start = datetime.now () c = pythonsum (size) delta = datetime.now ()-start# print 'The last 2 elements of the sum',c [- 2:] print' pythonSum elapsed time in microseconds',delta.microsecondssize = 1000start1 = datetime.now () C1 = numpysum (size) delta1 = datetime.now ()-start1# print 'The last 2 elements of the sum',c1 [- 2:] print' numpySum elapsed time in microseconds',delta1.microseconds

From the running results of the following program, we can see that the processing vector numpy is many times higher than the Python calculation.

PythonSum elapsed time in microseconds 1000numpySum elapsed time in microseconds 0 Thank you for your reading, the above is the content of "which is more efficient when adding vectors in Python and numpy". After the study of this article, I believe you have a more profound understanding of the problem of which vector addition is more efficient in Python and numpy, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Vectors efficiency two learning content situation results multiple that is forms ideas articles more knowledge knowledge points programs articles follow problems deal with Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Docker Shulou Tech Info macOS OPPO Reno