[SciPy-dev] Type handling of matrices

Pearu Peterson pearu at scipy.org
Wed Nov 17 04:26:54 EST 2004



On Wed, 17 Nov 2004, Nils Wagner wrote:

> BTW, how can I compute the gap function of A in scipy, where A is a dense 
> normal matrix
> and gap(A) is defined as follows
>
> gap(A) = \min\limits_{i \ne j} | \lambda_i-\lambda_j | / 2
>
> This approach seems to be not very efficient
>
> def gap(A):
> w = linalg.eigvals(A) # Compute the spectrum of A
> min = 1.e10 # Initialize

   ^^^ min is builtin function, don't use it as a variable name

> for i in len(w):

            ^^^^^^ you probably mean range(len(w)) here

> for j in len(w):
>       if i <> j:
>             min1 = abs(w[i]-w[j])
>             if min1 < min:
>                 min=min1
> return min/2

If len(w) is small then you should not worry about efficiency.
Anyway, by using

def gap(A)
  w = linalg.eigvals(A)
  mn = abs(w[0]-w[1])
  for i in range(len(w))
   for j in range(i):
      mn = min(mn,abs(w[i]-w[j]))
  return mn/2

should give speedup 2x at least.

Pearu




More information about the SciPy-Dev mailing list