bigdecimal-rs icon indicating copy to clipboard operation
bigdecimal-rs copied to clipboard

Divide by zero results in zero

Open sunjay opened this issue 6 years ago • 4 comments

Typically in Rust, dividing by zero results in a panic.

fn main() {
    let x = 1;
    let y = 0;
    x / y;
}
thread 'main' panicked at 'attempt to divide by zero', src/main.rs:4:5

In BigDecimal however, this just results in zero.

https://github.com/akubera/bigdecimal-rs/blob/71f19de6fbf4846ec9d88d2d1f03033bdc15509c/src/lib.rs#L987-L990

This is counter intuitive because it is inconsistent with the behaviour of other numbers in Rust.

I know that this topic is hotly debated, so I'm not talking about what is right, I'm talking about what is consistent in Rust.

Can the behaviour be changed to be consistent with other numbers in Rust? Is there some BigDecimal spec I don't know about that mandates dividing by zero being zero?

sunjay avatar Aug 22 '18 06:08 sunjay

I think the standard is to have a flag in the context object http://speleotrove.com/decimal/daexcep.html signalling that the value was divided by zero, and the value of the result being some representation of infinity.

I'll bring up this issue and get back to it later.

akubera avatar Aug 22 '18 14:08 akubera

I think it worth stick with rust defaults. For example you can check Div trait example itself: https://doc.rust-lang.org/std/ops/trait.Div.html

impl Rational {
    fn new(nominator: usize, denominator: usize) -> Self {
        if denominator == 0 {
            panic!("Zero is an invalid denominator!");
        }

        // Reduce to lowest terms by dividing by the greatest common
        // divisor.
        let gcd = gcd(nominator, denominator);
        Rational {
            nominator: nominator / gcd,
            denominator: denominator / gcd,
        }
    }
}

It clearly does panic.

Pzixel avatar Aug 22 '18 14:08 Pzixel

pushed to develop branch

akubera avatar Aug 22 '18 15:08 akubera

Inverse of 0 still returns 0: https://github.com/akubera/bigdecimal-rs/blob/master/src/lib.rs#L527

H2CO3 avatar Apr 19 '19 07:04 H2CO3