KASKADE 7 development version
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-2020 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
17namespace Kaskade
18{
23 // unfortunately not part of the standard C++99, but only GCC extension... here it is: <cmath>
24 // template <class R> R power(R,int) __attribute__((deprecated));
25 //
26 // No: std::pow works for built-in floating point values and std::complex only
27 // and calls transzendental functions, which may be slower than simple multiplication.
28
29 template <class R>
30 R power(R base, int exp)
31 {
32 if (exp>1 && exp%2==0) {
33 R p = power(base,exp/2);
34 return p*p;
35 }
36 else if (exp > 0)
37 return base * power(base,exp-1);
38 else if (exp < 0)
39 return static_cast<R>(1)/power(base,-exp);
40 else
41 return static_cast<R>(1);
42 }
43
48 template <class R>
49 R square(R x)
50 {
51 return x*x;
52 }
53
58 template <class R>
59 R faculty(int n)
60 {
61 R result = 1;
62 for (int i=2; i<=n; ++i)
63 result *= i;
64 return result;
65 }
66
70 namespace PowerDetails
71 {
72 // look for x^2 = n by bisection
73 constexpr int sqrti(int lo, int mid, int hi, int n)
74 {
75 return lo == hi ? lo
76 : n / mid < mid ? sqrti(lo,(lo+mid)/2,mid-1,n)
77 : sqrti(mid,(mid+hi+1)/2,hi,n);
78 }
79 }
88 constexpr int sqrti(int n)
89 {
90 return PowerDetails::sqrti(0,(n+1)/2,n,n);
91 }
92
93}
94
95#endif
R faculty(int n)
Computes faculties. Is this somewhere in the standard? no.
Definition: power.hh:59
R power(R base, int exp)
Computes integral powers of values in a multiplicative half-group.
Definition: power.hh:30
constexpr int sqrti(int n)
Computes floor(sqrt(n)) for integers n at compile time.
Definition: power.hh:88
R square(R x)
returns the square of its argument.
Definition: power.hh:49