-
-
Notifications
You must be signed in to change notification settings - Fork 359
add thomas alg in C++ #439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
#include <iostream> | ||
#include <vector> | ||
#include <cstring> | ||
|
||
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) { | ||
|
||
std::vector<double> y(size); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not have a normal array since you know it's size is fixed? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. trying to use C++ whenever possible so that it's cohesive, but i'll change it, no problem |
||
memset(y.data(), 0, size * sizeof(double)); | ||
|
||
y[0] = c[0] / b[0]; | ||
x[0] = x[0] / b[0]; | ||
|
||
for (size_t i = 1; i < size; ++i) { | ||
double scale = 1.0 / (b[i] - a[i] * y[i - 1]); | ||
y[i] = c[i] * scale; | ||
x[i] = (x[i] - a[i] * x[i - 1]) * scale; | ||
} | ||
|
||
for (int i = size - 2; i >= 0; --i) { | ||
x[i] -= y[i] * x[i + 1]; | ||
} | ||
} | ||
|
||
int main() { | ||
std::vector<double> a = {0.0, 2.0, 3.0}; | ||
std::vector<double> b = {1.0, 3.0, 6.0}; | ||
std::vector<double> c = {4.0, 5.0, 0.0}; | ||
std::vector<double> x = {7.0, 5.0, 3.0}; | ||
|
||
std::cout << "The system" << std::endl; | ||
std::cout << "[1.0 4.0 0.0][x] = [7.0]" << std::endl; | ||
std::cout << "[2.0 3.0 5.0][y] = [5.0]" << std::endl; | ||
std::cout << "[0.0 3.0 6.0][z] = [3.0]" << std::endl; | ||
std::cout << "has the solution" << std::endl; | ||
|
||
thomas(a, b, c, x, 3); | ||
|
||
for (size_t i = 0; i < 3; ++i) { | ||
std::cout << "[" << x[i] << "]" << std::endl; | ||
} | ||
|
||
return 0; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You don't need size when you have
a.size()
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah that's true, i'll change it