Gram Schmidt处理列表清单

时间:2017-03-03 00:49:02

标签: python-2.7 numerical-methods

我的程序中的所有功能都可以工作,并且我已经使用我的IDE检查了它们。目前,在调用GramSchmidt函数后,我得到了ZeroDivisionError。回调导致GH2功能被调用和

return ConstMultv(w, -(VIP(v, w)/VIP(w, w)))

是发生错误的行。我已经使用其他向量测试了该函数,并且其功能正常(使用我的IDE)。请参阅下面的评论功能。

import math

def Addv(u, v):
    n = len(u)
    w = []
    for x in range(n):
        w.append(u[x] + v[x])
    return w

#Test
# u=[1,2]   
# v=[3,4]
# Addv(u,v)

def Subv(u, v):
    n = len(u)
    w = []
    for x in range(n):
        w.append(u[x] - v[x])
    return w    

# Subv(u,v)    

def ConstMultv(v,a):
    n = len(v)
    w = []
    for x in range(n):
        w.append(a*v[x])
    return w      

# a=3
# ConstMultv(v,a)    

def Normalizev(v):
    n=len(v)
    s=0.0
    for x in range(n):
        s=s+v[x]**2
    s=s**0.5
    return ConstMultv(v,1/s)    

# Normalizev(v)

# Now assume v is a list of lists
def Normalizea(v):
    m = len(v)
    w=[]
    for y in range(m):
        w.append(Normalizev(v[y]))
    return w    

# Normalizea([ [1,2],[3,4]]) 

def VIP(v, w):
    n = len(v)
    dot = 0
    for x in range (n) :
        dot = dot + v[x]*w[x]
    return dot

# VIP([1,2],[3,4])


# Compute (v_(k+1),w_i)/(w_i,w-i) w_i
def GSH2(v, w) :
     return ConstMultv(w, -(VIP(v, w)/VIP(w, w)))

# w=[1,1,2] 
# v=[2,3,4]
# GSH2(v,w)

def GSH(v, w) : 
    n=len(v)
    k=len(w)
    u = v
    for i in range(k) :
        u = Addv( u, GSH2(v,w[i])) 
    return (u) 

# w = [[1,1,2],[-1,-1,1]]
# v = [2,3,4]     
 # GSH(v,w)




def GramSchmidt(v) : 
    w = []
    m = len(v) 
    for k in range(m):
        w.append(GSH(v[k],w))
    return Normalizea(w) 

# v=[[1,1,2],[0,0,3],[2,3,4]]  
# GramSchmidt(v)  

##------------------------------------------------------Main Block----------------------------------------------------------------------------------------------------
c = input('Please enter the amount of vectors you will be entering: ')
n = input('Please enter the amount of elements in each vector : ')

v = [[0 for x in range(n)] for y in range(c)] 

for x in range (c) :
    for y in range (n) :
        v[x][y] = input('Please enter v_i: ')
        print str(v[x][y])

for x in range (c) :
    for y in range (n) :
        print 'v[' + str(x) + '][' + str(y) + '] = ' + str(v[x][y])
u = GramSchmidt(v)

for x in range (c) :
    print 'u[' + x + ']:'
    for y in range (n) :
        print '    u[' + str(x) + '][' + str(y) + '] = ' + str(u[x][y])

1 个答案:

答案 0 :(得分:0)

如果您为c输入3,为n输入2,v将为[[0 0 0][0 0 0]],但如果您对c和{{1}进行了描述我相信,你希望n成为v

此外,当您[[0 0][0 0][0 0]]到列表时,您可以更改其长度;这可能就是你没有看到输入值的原因。