Skip to content

Commit

Permalink
simplify op_div
Browse files Browse the repository at this point in the history
  • Loading branch information
arvidn committed Nov 11, 2021
1 parent 659f4a3 commit 9845ce6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/more_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,16 +430,13 @@ pub fn op_div(a: &mut Allocator, input: NodePtr, _max_cost: Cost) -> Response {
if a1.sign() == Sign::NoSign {
args.first()?.err("div with 0")
} else {
let q = &a0 / &a1;
let r = &a0 - &a1 * &q;
let (mut q, r) = a0.div_mod_floor(&a1);

// rust rounds division towards zero, but we want division to round
// toward negative infinity.
let q = if q.sign() == Sign::Minus && r.sign() != Sign::NoSign {
q - 1
} else {
q
};
// this is to preserve a buggy behavior from the initial implementation
// of this operator.
if q == (-1).into() && r != 0.into() {
q += 1;
}
let q1 = ptr_from_number(a, &q)?;
Ok(malloc_cost(a, cost, q1))
}
Expand Down
12 changes: 12 additions & 0 deletions src/test_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,13 @@ x "error_message" => FAIL
/ 1 10 => 0
/ -1 -10 => 0
/ 1 1 => 1
/ 1 -1 => -1
/ -1 -1 => 1
/ -1 1 => -1
/ 0 -1 => 0
/ 0 1 => 0
; these results are incorrect.
; the result should be -1
; the / operator is deprecated because of this
Expand Down Expand Up @@ -486,6 +493,11 @@ divmod -1 3 => ( -1 . 2 )
divmod -1 -3 => ( 0 . -1 )
divmod 1 -3 => ( -1 . -2 )
divmod 1 1 => ( 1 . 0 )
divmod -1 1 => ( -1 . 0 )
divmod -1 -1 => ( 1 . 0 )
divmod 1 -1 => ( -1 . 0 )
divmod 1 10 => ( 0 . 1 )
divmod 1 -10 => ( -1 . -9 )
divmod -1 -10 => ( 0 . -1 )
Expand Down

0 comments on commit 9845ce6

Please sign in to comment.