From 4b0ba821672cfffe6405a19a386a3b4ffb0ea272 Mon Sep 17 00:00:00 2001 From: Wolfgang Bangerth Date: Wed, 10 Jan 2024 16:07:41 -0700 Subject: [PATCH] Use std::abs() when computing the norm of a tensor of size 1. --- include/deal.II/base/tensor.h | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/include/deal.II/base/tensor.h b/include/deal.II/base/tensor.h index 56eaa02ef5..49bbcc5a25 100644 --- a/include/deal.II/base/tensor.h +++ b/include/deal.II/base/tensor.h @@ -1720,9 +1720,27 @@ template inline DEAL_II_HOST_DEVICE typename numbers::NumberTraits::real_type Tensor::norm() const { - // Make things work with AD types - using std::sqrt; - return sqrt(norm_square()); + // Handle cases of a tensor consisting of just one number more + // efficiently: + if constexpr ((rank_ == 1) && (dim == 1) && std::is_arithmetic_v) + { + return std::abs(values[0]); + } + else if constexpr ((rank_ == 2) && (dim == 1) && std::is_arithmetic_v) + { + return std::abs(values[0][0]); + } + else + { + // Otherwise fall back to the naive algorithm of taking the square root of + // the sum of squares. + + // Make things work with AD types by letting the compiler look up + // the symbol sqrt in namespace std and in the type-associated + // namespaces + using std::sqrt; + return sqrt(norm_square()); + } } -- 2.39.5