Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Vector normalization

The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector.

Am I doing this right in Python code?

Vvx = 0-xi  # view vector (calculating it from surface points)
Vvy = 0-yi
Vvz = 0-zi
Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz))  # normalizing
Vvx = Vvx / Vv
Vvy = Vvy / Vv
Vvz = Vvz / Vv
Lv = (1,1,1)  # light vector
Hn = math.sqrt(((1 + Vvx) * (1 + Vvx)) + ((1 + Vvy) * (1 + Vvy)) +
               ((1 + Vvz) * (1 + Vvz))) 
Hv = ((1 + Vvx) / Hn, (1 + Vvy) / Hn, (1 + Vvz) / Hn)  # half-way vector
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is misnamed. What you've written is simple vector addition of two vectors, with the result being a normalized unit vector.

Here's how I'd do it:

import math

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

if __name__ == '__main__':
    l = [1, 1, 1]
    v = [0, 0, 0]

    h = normalize(add(l, v))
    print h

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...