Skip to content

Commit

Permalink
Merge branch 'cubic_root_mess_fix' into 'master'
Browse files Browse the repository at this point in the history
Replaced 'nan' by numeric value for repeated roots

See merge request ogs/ogs!5177
  • Loading branch information
bilke committed Dec 20, 2024
2 parents 9a1da6a + b6ce996 commit 88ce811
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
33 changes: 23 additions & 10 deletions MathLib/Nonlinear/CubicRoots.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,36 @@ class CubicSolver
}
}

// Method to solve the cubic equation using Boost
std::vector<double> solve()
{
// Solve using Boost's cubic_roots
std::array<double, 3> const roots =
boost::math::tools::cubic_roots<double>(a_, b_, c_, d_);

std::vector<double> filtered_roots =
ranges::views::ref(roots) |
ranges::views::filter([](double const root)
{ return !std::isnan(root); }) |
ranges::to<std::vector>();
ranges::sort(filtered_roots);
std::vector<double> adjusted_roots;
adjusted_roots.reserve(3);

return filtered_roots;
}
double last_valid = std::numeric_limits<double>::quiet_NaN();

for (auto root : roots)
{
if (std::isnan(root))
{
if (!std::isnan(last_valid))
{
adjusted_roots.push_back(last_valid);
}
// If we get NaN before any valid root, we just skip it
}
else
{
adjusted_roots.push_back(root);
last_valid = root;
}
}

ranges::sort(adjusted_roots);
return adjusted_roots;
}
// Method that returns the smallest positive real root
double smallestPositiveRealRoot()
{
Expand Down
2 changes: 1 addition & 1 deletion Tests/MathLib/TestCubicRoots.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ TEST(MathLibCubicSolver, CubicEquationWithComplexRoots)
MathLib::CubicSolver solver(1.0, 0.0, -1.0, 1.0);
auto roots = solver.solve();

ASSERT_EQ(roots.size(), 1); // Only one real root should be found
ASSERT_EQ(roots.size(), 3); // Only one real root should be found
EXPECT_NEAR(roots[0], -1.3247,
1e-4); // Check against the expected real root
}
Expand Down

0 comments on commit 88ce811

Please sign in to comment.