cgv
Loading...
Searching...
No Matches
lu.h
1#pragma once
2
3#include <cgv/math/mat.h>
4#include <cgv/math/perm_mat.h>
5#include <cgv/math/low_tri_mat.h>
6#include <cgv/math/up_tri_mat.h>
7#include <cgv/math/vec.h>
8#include <limits>
9#include <algorithm>
10
11namespace cgv {
12namespace math {
13
16template <typename T>
17bool lu(const mat<T> &a,perm_mat& p, low_tri_mat<T>& l, up_tri_mat<T>& u)
18{
19
20
21 unsigned n = a.nrows();
22 unsigned m = a.ncols();
23 assert(n==m);
24 l.resize(n);
25 u.resize(n);
26 p.resize(n);
27
28 for(unsigned i =0; i < a.ncols();i++)
29 for(unsigned j = 0; j < a.nrows();j++)
30 {
31 if(i > j)
32 l(i,j) = a(i,j);
33 else
34 u(i,j) = a(i,j);
35 }
36
37
38
39 const T eps=std::numeric_limits<T>::epsilon();
40 unsigned i,imax,j,k;
41 T big,temp;
42 vec<T> vv(n);
43 T d=1.0;
44
45 for (i=0;i<n;i++)
46 {
47 big=0.0;
48 for (j=0;j<n;j++)
49 {
50 if(i > j)
51 {
52 if ((temp=std::abs(l(i,j))) > big)
53 big=temp;
54 }
55 else
56 {
57 if ((temp=std::abs(u(i,j))) > big)
58 big=temp;
59 }
60
61
62 }
63 if (big == 0.0) return false;
64 vv[i]=(T)1.0/big;
65 }
66 for (k=0;k<n;k++)
67 {
68 big=0.0;
69 for (i=k;i<n;i++)
70 {
71 if(i > k)
72 temp=vv[i]*std::abs(l(i,k));
73 else
74 temp=vv[i]*std::abs(u(i,k));
75
76 if (temp > big)
77 {
78 big=temp;
79 imax=i;
80 }
81 }
82 if (k != imax)
83 {
84 for (j=0;j<n;j++)
85 {
86 if(imax > j)
87 {
88 temp=l(imax,j);
89 if(k > j)
90 {
91 l(imax,j)=l(k,j);
92 l(k,j)=temp;
93 }
94 else
95 {
96 l(imax,j)=u(k,j);
97 u(k,j)=temp;
98 }
99
100 }
101 else
102 {
103 temp=u(imax,j);
104 if(k > j)
105 {
106 u(imax,j)=l(k,j);
107 l(k,j)=temp;
108 }
109 else
110 {
111 u(imax,j)=u(k,j);
112 u(k,j)=temp;
113 }
114 }
115
116
117 }
118 d = -d;
119 vv[imax]=vv[k];
120
121 }
122 p.swap(imax,k);
123
124 if (u(k,k) == 0.0) u(k,k)=eps;
125 for (i=k+1;i<n;i++)
126 {
127
128 temp=l(i,k) /= u(k,k);
129
130 for (j=k+1;j<n;j++)
131 {
132 if(i > j)
133 l(i,j) -= temp*u(k,j);
134 else
135 u(i,j) -= temp*u(k,j);
136 }
137 }
138 }
139 for(unsigned i = 0; i < n; i++)
140 {
141
142 l(i,i)=(T)1;
143
144 }
145
146
147 return true;
148}
149
150
151
152}
153
154}
the cgv namespace
Definition print.h:11