本文主要是介绍Sweet Snippet 之 Gram-Schmidt 正交化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Gram-Schmidt 正交化的简单实现
Gram-Schmidt(格拉姆-施密特) 正交化可以正交化一组给定的向量,使这些向量两两垂直,这里列出一份简单的实现(Lua):
-- vector add
function add(a, b)if a and b and #a == #b thenlocal ret = {}for i = 1, #a dotable.insert(ret, a[i] + b[i])endreturn retend
end-- vector sub
function sub(a, b)if a and b and #a == #b thenlocal ret = {}for i = 1, #a dotable.insert(ret, a[i] - b[i])endreturn retend
end-- dot product
function dot(a, b)if a and b and #a == #b thenlocal ret = 0for i = 1, #a doret = ret + a[i] * b[i]endreturn retend
end-- magnitude
function mag(a)local val = dot(a, a)if val thenreturn math.sqrt(val)end
end-- normalize, do not change param
function norm(a)local magnitude = mag(a)if magnitude and magnitude ~= 0 thenlocal normalize = {}for i = 1, #a dotable.insert(normalize, a[i] / magnitude)endreturn normalizeend
end-- project a to b
function proj(a, b)if a and b and #a == #b thenlocal norm_b = norm(b)local val = dot(a, norm_b)if val thenlocal projection = {}for i = 1, #norm_b dotable.insert(projection, norm_b[i] * val)endreturn projectionendend
end-- perpendicular a to b
function perp(a, b)local projection = proj(a, b)if projection thenreturn sub(a - projection)end
end-- gram schmidt
function gram_schmidt(...)local vecs = { ... }local ret = {}if #vecs > 0 thentable.insert(ret, vecs[1])endfor i = 2, #vecs dolocal base = vecs[i]for j = 1, i - 1 dobase = sub(base, proj(vecs[i], vecs[j]))endtable.insert(ret, base)vecs[i] = baseendreturn table.unpack(ret)
end-- use to check gram schmidt result
function check_perp(...)local vecs = { ... }for i = 1, #vecs - 1 dofor j = i + 1, #vecs dolocal val = dot(vecs[i], vecs[j])if math.abs(val) > 0.001 thenreturn falseendendendreturn true
end
有兴趣的朋友可以试试这组向量的 Gram-Schmidt 正交化:
a = ( 1 , 0 , 0 , 1 ) b = ( 0 , 1 , 0 , 1 ) c = ( 0 , 0 , 1 , 1 ) d = ( 0 , 1 , 1 , 1 ) \begin{aligned} & a = ( 1, 0, 0, 1 ) \\ & b = ( 0, 1, 0, 1 ) \\ & c = ( 0, 0, 1, 1 ) \\ & d = ( 0, 1, 1, 1 ) \end{aligned} a=(1,0,0,1)b=(0,1,0,1)c=(0,0,1,1)d=(0,1,1,1)
更多资料
- wiki
这篇关于Sweet Snippet 之 Gram-Schmidt 正交化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!