bigdecimal-rs
bigdecimal-rs copied to clipboard
Divide by zero results in zero
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?
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.
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.
pushed to develop branch
Inverse of 0 still returns 0: https://github.com/akubera/bigdecimal-rs/blob/master/src/lib.rs#L527