1 from sage
.modules
.free_module_element
import vector
2 from sage
.rings
.number_field
.number_field
import NumberField
3 from sage
.rings
.polynomial
.polynomial_ring_constructor
import PolynomialRing
4 from sage
.rings
.real_lazy
import RLF
7 return vector(m
.base_ring(), m
.list())
11 Perform Gram-Schmidt on the list ``v`` which are assumed to be
12 vectors over the same base ring. Returns a list of orthonormalized
13 vectors over the smallest extention ring containing the necessary
18 sage: from mjo.eja.eja_utils import gram_schmidt
22 sage: v1 = vector(QQ,(1,2,3))
23 sage: v2 = vector(QQ,(1,-1,6))
24 sage: v3 = vector(QQ,(2,1,-1))
26 sage: u = gram_schmidt(v)
27 sage: all( u_i.inner_product(u_i).sqrt() == 1 for u_i in u )
29 sage: u[0].inner_product(u[1]) == 0
31 sage: u[0].inner_product(u[2]) == 0
33 sage: u[1].inner_product(u[2]) == 0
38 Ensure that zero vectors don't get in the way::
40 sage: v1 = vector(QQ,(1,2,3))
41 sage: v2 = vector(QQ,(1,-1,6))
42 sage: v3 = vector(QQ,(0,0,0))
44 sage: len(gram_schmidt(v)) == 2
49 return (y
.inner_product(x
)/x
.inner_product(x
))*x
51 v
= list(v
) # make a copy, don't clobber the input
53 # Drop all zero vectors before we start.
54 v
= [ v_i
for v_i
in v
if not v_i
.is_zero() ]
62 # First orthogonalize...
63 for i
in xrange(1,len(v
)):
64 # Earlier vectors can be made into zero so we have to ignore them.
65 v
[i
] -= sum( proj(v
[j
],v
[i
]) for j
in range(i
) if not v
[j
].is_zero() )
67 # And now drop all zero vectors again if they were "orthogonalized out."
68 v
= [ v_i
for v_i
in v
if not v_i
.is_zero() ]
70 # Now pretend to normalize, building a new ring R that contains
71 # all of the necessary square roots.
72 norms_squared
= [0]*len(v
)
74 for i
in xrange(len(v
)):
75 norms_squared
[i
] = v
[i
].inner_product(v
[i
])
76 ns
= [norms_squared
[i
].numerator(), norms_squared
[i
].denominator()]
78 # Do the numerator and denominator separately so that we
79 # adjoin e.g. sqrt(2) and sqrt(3) instead of sqrt(2/3).
80 for j
in xrange(len(ns
)):
81 PR
= PolynomialRing(R
, 'z')
84 if p
.is_irreducible():
87 embedding
=RLF(ns
[j
]).sqrt())
89 # When we're done, we have to change every element's ring to the
90 # extension that we wound up with, and then normalize it (which
91 # should work, since "R" contains its norm now).
92 for i
in xrange(len(v
)):
93 v
[i
] = v
[i
].change_ring(R
) / R(norms_squared
[i
]).sqrt()