Skip to main content

deep_time/math/
powi.rs

1use crate::Real;
2
3/// Raises a floating-point number to an integer power.
4///
5/// Fully handles `i32::MIN` without overflow.
6#[must_use]
7pub const fn powi(base: Real, exp: i32) -> Real {
8    if exp == 0 {
9        return 1.0;
10    }
11    if exp == 1 {
12        return base;
13    }
14    if exp == -1 {
15        return 1.0 / base;
16    }
17
18    let mut result = f!(1.0);
19    let mut b = if exp < 0 { 1.0 / base } else { base };
20    let mut e = exp.unsigned_abs();
21
22    while e > 0 {
23        if e & 1 == 1 {
24            result *= b;
25        }
26        b *= b;
27        e >>= 1;
28    }
29
30    result
31}