Simplify the loop code --- vectorization

Calculate the sum of squares of 1~5

The loop code is as follows:

A=[1,2,3,4,5]
B=[1,2,3,4,5]
res=0
for i in range(0,5):
	res+=A[i]*B[i]

The vectorization code is as follows:

import numpy as np
A=[1,2,3,4,5]
B=[1,2,3,4,5]
res=np.dot(A,B)

The most critical line in the above code is np.dot(A,BT). The dot method performs a vector multiplication operation. After this treatment, it is said that it can increase the running speed by 300 times~~~~~

Guess you like

Origin blog.csdn.net/qq_42697271/article/details/113617132