Skip to content

Commit 12cdf1d

Browse files
YordrarKen Power
authored and
Ken Power
committed
add thomas alg in C++
1 parent 7767ee4 commit 12cdf1d

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cstring>
4+
5+
void thomas(std::vector<double> const a, std::vector<double> const b, std::vector<double> const c, std::vector<double>& x, const size_t size) {
6+
7+
std::vector<double> y(size);
8+
memset(y.data(), 0, size * sizeof(double));
9+
10+
y[0] = c[0] / b[0];
11+
x[0] = x[0] / b[0];
12+
13+
for (size_t i = 1; i < size; ++i) {
14+
double scale = 1.0 / (b[i] - a[i] * y[i - 1]);
15+
y[i] = c[i] * scale;
16+
x[i] = (x[i] - a[i] * x[i - 1]) * scale;
17+
}
18+
19+
for (int i = size - 2; i >= 0; --i) {
20+
x[i] -= y[i] * x[i + 1];
21+
}
22+
}
23+
24+
int main() {
25+
std::vector<double> a = {0.0, 2.0, 3.0};
26+
std::vector<double> b = {1.0, 3.0, 6.0};
27+
std::vector<double> c = {4.0, 5.0, 0.0};
28+
std::vector<double> x = {7.0, 5.0, 3.0};
29+
30+
std::cout << "The system" << std::endl;
31+
std::cout << "[1.0 4.0 0.0][x] = [7.0]" << std::endl;
32+
std::cout << "[2.0 3.0 5.0][y] = [5.0]" << std::endl;
33+
std::cout << "[0.0 3.0 6.0][z] = [3.0]" << std::endl;
34+
std::cout << "has the solution" << std::endl;
35+
36+
thomas(a, b, c, x, 3);
37+
38+
for (size_t i = 0; i < 3; ++i) {
39+
std::cout << "[" << x[i] << "]" << std::endl;
40+
}
41+
42+
return 0;
43+
}

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,10 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
113113
[import, lang:"haskell"](code/haskell/thomas.hs)
114114
{% sample lang="swift" %}
115115
[import, lang:"swift"](code/swift/thomas.swift)
116+
{% sample lang="cpp" %}
117+
[import, lang:"c_cpp"](code/c++/thomas.cpp)
116118
{% endmethod %}
117119

118120
<script>
119121
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
120-
</script>
122+
</script>

0 commit comments

Comments
 (0)