#306 Aug 8, 2026

306. powi — Integer Powers Without the powf Detour

x * x * x doesn’t scale, and powf(3.0) routes an integer exponent through the full floating-point pow machinery. powi is the method built for exactly this case.

Three ways to cube a float:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let x: f64 = 1.05;

// the hand-rolled chain
let cubed = x * x * x;

// powf: full transcendental pow
let cubed = x.powf(3.0);

// powi: integer exponent, fast path
let cubed = x.powi(3);

The chain stops being readable past the third power and can’t handle a runtime exponent at all. powf works, but it’s the general routine — built to handle any real exponent, when all you have is a small integer.

powi takes an i32 and computes the power by repeated multiplication. Negative exponents give you the reciprocal, no 1.0 / dance:

1
assert_eq!(2.0_f64.powi(-3), 0.125); // 1 / 2³

The quieter win is negative bases. As bite 302 showed with cbrt, powf on a negative base is one fractional exponent away from NaN. With powi the exponent is an integer by construction, so the sign question always has an answer:

1
2
assert_eq!((-3.0_f64).powi(2), 9.0);
assert_eq!((-3.0_f64).powi(3), -27.0);

Compound growth is the everyday use case — the exponent is a year count, not a real number:

1
2
3
4
5
6
let balance: f64 = 1_000.0;
let rate: f64 = 0.05;
let years: i32 = 10;

let future = balance * (1.0 + rate).powi(years);
assert!((future - 1_628.89).abs() < 0.01);

If the exponent in your powf call ends in .0, it wants to be a powi.

← Previous 305. to_bits — Hash and Dedup Floats Without a Wrapper Crate Next → 307. to_degrees / to_radians — Stop Hand-Typing 180.0 / PI