KASKADE 7 development version
Loading...
Searching...
No Matches
power.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2002-2025 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef UTILITIES_POWER_HH
14#define UTILITIES_POWER_HH
15
16#include <cassert>
17
18namespace Kaskade
19{
24 // unfortunately not part of the standard C++99, but only GCC extension... here it is: <cmath>
25 // template <class R> R power(R,int) __attribute__((deprecated));
26 //
27 // No: std::pow works for built-in floating point values and std::complex only
28 // and calls transzendental functions, which may be slower than simple multiplication.
29
30 template <class R>
31 constexpr R power(R base, int exp)
32 {
33 if (exp>1 && exp%2==0)
34 {
35 R p = power(base,exp/2);
36 return p*p;
37 }
38 else if (exp > 0)
39 return base * power(base,exp-1);
40 else if (exp < 0)
41 return static_cast<R>(1)/power(base,-exp);
42 else
43 return static_cast<R>(1);
44 }
45
50 template <class R>
51 constexpr R square(R x)
52 {
53 return x*x;
54 }
55
56 // ----------------------------------------------------------------------------------------------
57
62 template <class R>
63 constexpr R faculty(int n)
64 {
65 assert(n>=0);
66
67 R result = 1;
68 for (int i=2; i<=n; ++i)
69 result *= i;
70 return result;
71 }
72
73 // ----------------------------------------------------------------------------------------------
74
78 namespace PowerDetails
79 {
80 // look for x^2 = n by bisection
81 constexpr int sqrti(int lo, int mid, int hi, int n)
82 {
83 return lo == hi ? lo
84 : n / mid < mid ? sqrti(lo,(lo+mid)/2,mid-1,n)
85 : sqrti(mid,(mid+hi+1)/2,hi,n);
86 }
87 }
91
96 constexpr int sqrti(int n)
97 {
98 return PowerDetails::sqrti(0,(n+1)/2,n,n);
99 }
100
101}
102
103#endif
constexpr R power(R base, int exp)
Computes integral powers of values in a multiplicative half-group.
Definition power.hh:31
constexpr int sqrti(int n)
Computes floor(sqrt(n)) for integers n at compile time.
Definition power.hh:96
constexpr R square(R x)
returns the square of its argument.
Definition power.hh:51
constexpr R faculty(int n)
Computes faculties. Is this somewhere in the standard? no.
Definition power.hh:63