tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,3 @@
>load incidence;
>{u,r}=solvePotentialX(makeRectangleX(10,10),12,68); r,
1.60899124173

View file

@ -0,0 +1,44 @@
function makeRectangleX (n:index,m:index)
## Make the incidence matrix of a rectangle grid in compact form.
## see: makeRectangleIncidence
K=zeros(n*(m-1)+m*(n-1),3);
k=1;
for i=1 to n;
for j=1 to m-1;
K[k,1]=(i-1)*m+j; K[k,2]=(i-1)*m+j+1; K[k,3]=1;
k=k+1;
end;
end;
for i=1 to n-1;
for j=1 to m;
K[k,1]=(i-1)*m+j; K[k,2]=i*m+j; K[k,3]=1;
k=k+1;
end;
end;
H=cpxzeros([n*m,n*m]);
H=cpxset(H,K);
H=cpxset(H,K[:,[2,1,3]]);
return H;
endfunction
function solvePotentialX (A:cpx, i:index ,j:index)
## Solve the potential problem of resistance in a graph.
## This functions uses the conjugate gradient method.
## A is a compressed incidence matrix.
## Return the potential u for the nodes in A,
## such that u[i]=1, u[j]=-1, and the flow
## to each knot is equal to the flow from the knot,
## and the flow from i to j is (u[i]-u[j])*A[i,j].
## see: makeIncidence
n=size(A)[1];
b=ones(n,1); f=-cpxmult(A,b);
h=1:n; B=cpxset(A,h'|h'|f);
B=cpxset(B,i|h'|0);
B=cpxset(B,[i,i,1]);
B=cpxset(B,j|h'|0);
B=cpxset(B,[j,j,1]);
v=zeros(n,1); v[i]=1; v[j]=-1;
u=cpxfit(B,v);
f=(-f[i])*u[i]-cpxmult(A,u)[i];
return {u,2/f}
endfunction

View file

@ -0,0 +1,39 @@
function cgX (H:cpx, b:real column, x0:real column=none, f:index=10)
## Conjugate gradient method to solve Hx=b for compressed H.
##
## This is the method of choice for large, sparse matrices. In most
## cases, it will work well, fast, and accurate.
##
## H must be positive definite. Use cpxfit, if it is not.
##
## The accuarcy can be controlled with an additional parameter
## eps. The algorithm stops, when the error gets smaller then eps, or
## after f*n iterations, if the error gets larger. x0 is an optional
## start vector.
##
## H : compressed matrix (nxm)
## b : column vector (mx1)
## x0 : optional start point (mx1)
## f : number of steps, when the method should be restarted
##
## See: cpxfit, cg, cgXnormal
if isvar("eps") then localepsilon(eps); endif;
n=cols(H);
if x0==none then x=zeros(size(b));
else; x=x0;
endif;
loop 1 to 10
r=b-cpxmult(H,x); p=r; fehler=r'.r;
loop 1 to f*n
if sqrt(fehler)~=0 then return x; endif;
Hp=cpxmult(H,p);
a=fehler/(p'.Hp);
x=x+a*p;
rn=r-a*Hp;
fehlerneu=rn'.rn;
p=rn+fehlerneu/fehler*p;
r=rn; fehler=fehlerneu;
end;
end;
return x;
endfunction