From a7d76ae20aed647673dce37334b04917fbe41012 Mon Sep 17 00:00:00 2001 From: Matthias Maier Date: Thu, 5 Sep 2019 18:08:55 -0500 Subject: [PATCH] Utilities::fixed_power - use exponentiation by squaring --- include/deal.II/base/utilities.h | 28 ++++++++-------------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/include/deal.II/base/utilities.h b/include/deal.II/base/utilities.h index 00442d9d9d..4c9ae69d84 100644 --- a/include/deal.II/base/utilities.h +++ b/include/deal.II/base/utilities.h @@ -1030,27 +1030,15 @@ namespace Utilities { template inline T - fixed_power(const T n) + fixed_power(const T x) { - Assert(N >= 0, ExcNotImplemented()); - switch (N) - { - case 0: - return dealii::internal::NumberType::value(1); - case 1: - return n; - case 2: - return n * n; - case 3: - return n * n * n; - case 4: - return n * n * n * n; - default: - T result = n; - for (int d = 1; d < N; ++d) - result *= n; - return result; - } + if (N == 0) + return T(1.); + else if (N < 0) + return T(1.) / fixed_power<-N>(x); + else + // Use exponentiation by squaring: + return ((N % 2 == 1) ? x * fixed_power(x * x) : fixed_power(x * x)); } -- 2.39.5