book icon indicating copy to clipboard operation
book copied to clipboard

Chapter 3.2: Integer division rounding is described incorrectly

Open jruderman opened this issue 4 years ago • 1 comments
trafficstars

  • [x] I have checked the latest main branch to see if this has already been fixed
  • [x] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem:

https://doc.rust-lang.org/book/ch03-02-data-types.html#numeric-operations (but only in a newer version than on the web site)

Description of the problem:

With the fix for #2248, the book states:

Integer division rounds down to the nearest integer.

and has the example:

let floored = 2 / 3; // Results in 0

However, on godbolt, the behavior I observe is instead truncation toward zero.

fn main()
{
    println!("{}", (-9) / (4));
    println!("{}", (9) / (-4));
    println!("{}", (-9) / (-4));
}

outputs

-2
-2
2

I believe this is true on all architectures supported by Rust: the Rust Reference states "Integer division rounds towards zero."

Suggested fix:

  • "Integer division rounds toward zero" or "Integer division truncates toward zero"
  • Change floored to truncated or rounded_toward_zero

jruderman avatar Sep 09 '21 13:09 jruderman

This isn't right yet. Currently, the code listing for the ch03-02 Numeric Operations section says:

let floored = 2 / 3; // Results in 0

Instead, it should say:

let truncated = 2 / 3; // Results in 0

Consider how integer division and flooring work. Integer division results in truncation—and not in flooring. For example, this code:

fn main() {
    let below_negative_two: f32 = -9.0 / 4.0;  // This equals -2.25
    let floored = below_negative_two.floor();
    println!("Floored: {:?}", floored);

    let truncated = -9 / 4;
    println!("Truncated: {:?}", truncated);
}

produces this result:

Floored: -3.0
Truncated: -2

MarkDBlackwell avatar Mar 13 '22 15:03 MarkDBlackwell