SDDSlib
Loading...
Searching...
No Matches
ipow.c
Go to the documentation of this file.
1/**
2 * @file ipow.c
3 * @brief This file provides the ipow function for computing integer powers of a double.
4 *
5 * @copyright
6 * - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7 * - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8 *
9 * @license
10 * This file is distributed under the terms of the Software License Agreement
11 * found in the file LICENSE included with this distribution.
12 *
13 * @author M. Borland, C. Saunders, R. Soliday
14 */
15
16#include "mdb.h"
17
18/**
19 * @brief Compute x raised to the power p (x^p).
20 *
21 * Uses straightforward repeated multiplication for efficiency,
22 * which can be faster than using pow() for integer exponents.
23 *
24 * Special cases:
25 * - If x = 0 and p < 0, an error is reported since division by zero occurs.
26 * - If p = 0, the result is 1.0.
27 * - If p < 0, the result is 1/(x^(-p)).
28 *
29 * @param[in] x The base value.
30 * @param[in] p The integer exponent.
31 * @return The computed value of x raised to the power p.
32 */
33double ipow(const double x, const int64_t p) {
34 double hp;
35 int64_t n;
36
37 if (x == 0) {
38 if (p < 0)
39 bomb("Floating divide by zero in ipow().", NULL);
40 return (p == 0 ? 1. : 0.);
41 }
42
43 if (p < 0)
44 return (1. / ipow(x, -p));
45
46 switch (p) {
47 case 0:
48 return (1.);
49 case 1:
50 return (x);
51 case 2:
52 return (x * x);
53 case 3:
54 hp = x * x;
55 return (hp * x);
56 case 4:
57 hp = x * x;
58 return (hp * hp);
59 case 5:
60 hp = x * x;
61 return (hp * hp * x);
62 case 6:
63 hp = x * x;
64 return (hp * hp * hp);
65 case 7:
66 hp = x * x * x;
67 return (hp * hp * x);
68 case 8:
69 hp = x * x;
70 hp = hp * hp;
71 return (hp * hp);
72 default:
73 n = p / 2;
74 hp = ipow(x, n);
75 switch (p - 2 * n) {
76 case 0:
77 return (hp * hp);
78 case 1:
79 return (hp * hp * x);
80 }
81 break;
82 }
83 return (0.); /* never actually executed--keeps compiler happy */
84}
void bomb(char *error, char *usage)
Reports error messages to the terminal and aborts the program.
Definition bomb.c:26
double ipow(const double x, const int64_t p)
Compute x raised to the power p (x^p).
Definition ipow.c:33