Loading...
Searching...
No Matches
Operators.tpp
1/*---------------------------------------------------------------------------*\
2 *
3 * bitpit
4 *
5 * Copyright (C) 2015-2021 OPTIMAD engineering Srl
6 *
7 * -------------------------------------------------------------------------
8 * License
9 * This file is part of bitpit.
10 *
11 * bitpit is free software: you can redistribute it and/or modify it
12 * under the terms of the GNU Lesser General Public License v3 (LGPL)
13 * as published by the Free Software Foundation.
14 *
15 * bitpit is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18 * License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with bitpit. If not, see <http://www.gnu.org/licenses/>.
22 *
23\*---------------------------------------------------------------------------*/
24
25// Operator "sign" ------------------------------------------------------------------- //
38template <class T>
40 const T & val
41 ){
42 return (T(0) < val) - (val < T(0)) ;
43};
44
55template <class T>
56T uipow(const T & base, unsigned int exponent)
57{
58 switch (exponent) {
59
60 case 0:
61 {
62 return 1;
63 }
64
65 case 1:
66 {
67 return base;
68 }
69
70 case 2:
71 {
72 return base * base;
73 }
74
75 case 3:
76 {
77 return base * base * base;
78 }
79
80 default:
81 {
82 // The integer power is evluated using the exponentiating by squaring
83 // algorithm. For an explanation of the algorith see the following
84 // link:
85 //
86 // https://en.wikipedia.org/wiki/Exponentiation_by_squaring
87 T result = static_cast<T>(1);
88 T base_work = base;
89 while (exponent) {
90 if (exponent % 2) {
91 result *= base_work;
92 }
93
94 exponent /= 2;
95 base_work *= base_work;
96 }
97
98 return result;
99 }
100
101 }
102}
T sign(const T &val)
Definition Operators.tpp:39
T uipow(const T &base, unsigned int exponent)
Definition Operators.tpp:56