Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

python - Concisely write vector expression in numpy?

Say I have two vectors: v1 = [1,2,3,4], v2 = [4,5,6,7]. I then wish to compute the expression(for some reason stackoverflow does not support latex, so I will take a picture enter image description here

I am by no means a master of NumPy, so I would write this in python as

sum = 0
for i in range(K):
    exp1 = np.sqrt(v1[i]*v2[i])
    sum += exp1

I am almost 100% sure that this can be done much more concisely. How would you write this mathematical expression?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, don't use sum for variable. Second, try:

out = np.sqrt(np.sqrt(np.dot(v1,v2))).sum()
# out:
# 2.783157683713741

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...