SDDSlib
Loading...
Searching...
No Matches
ipow.c File Reference

This file provides the ipow function for computing integer powers of a double. More...

#include "mdb.h"

Go to the source code of this file.

Functions

double ipow (const double x, const int64_t p)
 Compute x raised to the power p (x^p).
 

Detailed Description

This file provides the ipow function for computing integer powers of a double.

License
This file is distributed under the terms of the Software License Agreement found in the file LICENSE included with this distribution.
Author
M. Borland, C. Saunders, R. Soliday

Definition in file ipow.c.

Function Documentation

◆ ipow()

double ipow ( const double x,
const int64_t p )

Compute x raised to the power p (x^p).

Uses straightforward repeated multiplication for efficiency, which can be faster than using pow() for integer exponents.

Special cases:

  • If x = 0 and p < 0, an error is reported since division by zero occurs.
  • If p = 0, the result is 1.0.
  • If p < 0, the result is 1/(x^(-p)).
Parameters
[in]xThe base value.
[in]pThe integer exponent.
Returns
The computed value of x raised to the power p.

Definition at line 33 of file ipow.c.

33 {
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