From: Wolfgang Bangerth Date: Wed, 10 Jan 2024 23:07:41 +0000 (-0700) Subject: Use std::abs() when computing the norm of a tensor of size 1. X-Git-Tag: relicensing~171^2 X-Git-Url: https://gitweb.dealii.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F16458%2Fhead;p=dealii.git Use std::abs() when computing the norm of a tensor of size 1. --- 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()); + } }