A simple implementation of division in Rust

- 10 mins

We’ve taken a look at some basic theory for doing division in binary. In this post we implement the algorithm in Rust, benchmark how it performs and consequently apply a small optimization.

A naive implementation in Rust

Let’s jump straight into it! For our first implementation we’ll use the two’s complement method we reviewed in the last post:

pub fn div(dividend: u32, divisor: u32) -> (u32, u32) {
    // Get the two's complement of the number
    let ones_complement = divisor ^ 0xFFFF_FFFF;
    let twos_complement = ones_complement + 1;

    // Keep subtracting from the dividend until we can't anymore
    let mut working = dividend;
    let mut quotient = 0;
    while divisor <= working {
      working = working.wrapping_add(twos_complement);
      quotient += 1;
    }
    let remainder = working; // Leftover
    (quotient, remainder)
}

As expected, we get the two’s complement by reversing the bits (using an exclusive or) and adding one. We then continue looping and incrementing the quotient until we cannot subtract from the dividend without overflow.

This is a pretty naive implementation, however it works:

#[cfg(test)]
mod tests {
    use super::div;

    #[test]
    fn naive_div() {
        assert_eq!(div(100, 4), (25, 0));
        assert_eq!(div(100, 3), (33, 1));
    }
}

Understandably it performs worse as the final quotient gets bigger:

#![feature(test)]
extern crate division;
extern crate test;

use division::div;

#[bench]
fn div_hundred(b: &mut ::test::Bencher) {
    b.iter(|| {
        let result = div(100, 3);
        ::test::black_box(result);
    });
}

#[bench]
fn div_million(b: &mut ::test::Bencher) {
    b.iter(|| {
        let result = div(1_000_000, 3);
        ::test::black_box(result);
    });
}

#[bench]
fn div_billion(b: &mut ::test::Bencher) {
    b.iter(|| {
        let result = div(1_000_000_000, 3);
        ::test::black_box(result);
    });
}

On my machine, this is incredibly slow. Once it finally finishes it gives the following stats:

running 3 tests
test div_hundred ... bench:          22 ns/iter (+/- 3)
test div_million ... bench:      96,739 ns/iter (+/- 8,381)
test div_billion ... bench:  96,974,170 ns/iter (+/- 2,048,390)

test result: ok. 0 passed; 0 failed; 0 ignored; 3 measured; 0 filtered out

That doesn’t look too great! Let’s see if we can squeeze some better performance from this…

A quick optimization

We can get some much better performance based upon how binary numbers behave within a fixed sized type. With some simple optimizations I get the following benchmarked results:

running 3 tests
test div_billion ... bench:          55 ns/iter (+/- 3)
test div_hundred ... bench:          55 ns/iter (+/- 4)
test div_million ... bench:          55 ns/iter (+/- 4)

test result: ok. 0 passed; 0 failed; 0 ignored; 3 measured; 0 filtered out

That is some impressive improvement. It’s slightly slower for div_hundered however the rest are significantly faster. Let’s take a look at the code and then evaluate the results we’re seeing:

pub fn div2(dividend: u32, divisor: u32) -> (u32, u32) {
    // Get the two's complement of the number
    let ones_complement = divisor ^ 0xFFFF_FFFF;
    let twos_complement = ones_complement + 1;

    // Start off the quotient with the dividend
    let mut quotient = dividend;
    let mut remainder = 0u32;
    
    // Loop through the number of bits in the number (32)
    for _ in 0..32 {
      let carry = quotient >> 31;
      quotient = quotient << 1;
      remainder = remainder << 1;
      remainder = remainder | carry;

      let test = remainder.wrapping_add(twos_complement);
      if (test & 0x8000_0000) == 0 {
          remainder = test;
          quotient |= 1;
      }
    }

    (quotient, remainder)
}

As you can see, one of the major wins we get with this implementation is that we only loop 32 times as opposed to looping times. Of course, there are further optimizations we can achieve by early exiting on 1, when divisor = dividend etc but rather than jump into those… how is this even working?

Under the hood

This optimization is exploiting how binary numbers are represented in a fixed type system. I think that the easiest way to understand this is to go through a side by side example. To simplify, we’ll use a 4 bit number example: or

As you can see from the code, we start the algorithm off with the quotient being set to the dividend, and the remainder set to zero. We then start an sized loop whereby is the number of bits of the number we’re dividing - in this example: 4.

Let’s go through each iteration one by one and see what is happening…

Iteration 1

The first thing we’re doing is bit shifting the quotient and the remainder to the left. If you recall, bit shifting to the left is equivalent to doubling the number. Of course, in an bit number representation we may end up overflowing. With this algorithm, when we overflow the quotient we add one to the remainder, and when we overflow the remainder - we throw it away.

So if we double both the quotient and the remainder we get . can’t be represented in a 4 bit system so we subtract so that and add one to the remainder so that .

In binary, this is a bit easier to comprehend: we shift all the bits of the quotient and the remainder to the left and if a bit “overflows” from the quotient, we transfer it to the remainder: i.e.

The next part of this algorithm is a test… we check if we can subtract the divisor from the remainder. In this case you cannot subtract from without going into negative therefore this test fails.

The algorithm of course is doing this check via adding the two’s complement and checking if the left most digit is , thus indicating a positive number.

Iteration 2

We start off with the bit shift left / doubling of the number. For the quotient, doubling gives us which is perfectly fine. For the remainder doubled is which is also acceptable. In binary we of course have .

We then perform the test again. In this case subtracts from perfectly! Because of this, we add to the quotient and set the remainder to the result of the test (i.e. the leftover). In this case we set to .

Again, if we think about this from a binary perspective: once we’ve added the two’s complement to the remainder we detect that the result is positive. From this, we can assume that the “subtraction” was successful and consequently add one to the quotient (via bitwise OR) and set the remainder to the leftover.

Iteration 3

If we double/bit shift we get . The remainder is so we don’t do anything.

Performing the divisor test: we can’t subtract from so we continue on.

Iteration 4 - the final iteration

Doubling/bit shifting results in which of course has overflowed. So we subtract and move the bit (or add one) to the remainder making and .

If we perform the final test: we can see that the divisor does not subtract from the remainder cleanly therefore we stop our algorithm.

Consequently, we’re left with the result of our division which is: .

Conclusion

When utilizing binary numbers using a fixed size type system we’re able to achieve some optimizations for division that are difficult to achieve in other bases. Of course, this comes at a price - namely the numeric range that can be represented within that sized type.

We achieved a major performance boost from the naive implementation by simply rejigging the algorithm to exploit our type system. In the current form this isn’t all that useful, therefore in the next session we’ll take a look at how to logically represent decimal numbers with fractions and how we can consequently perform division on these.

For reference, all code examples above can be found on Github.

Paul Mason

Paul Mason

A kiwi engineer living in San Francisco

rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora