Uh oh!
There was an error while loading. Please reload this page.
Implement checked arithmetic - #152
Conversation
PaulXiCao
left a comment
There was a problem hiding this comment.
Looks good, just some smaller nitpicks from myside (disclosure: I am no maintainer here).
Additionally, do you think you could add tests for the newly introduced methods?
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
| impl<T: Clone + Num + CheckedAdd + CheckedSub + CheckedMul + CheckedDiv> CheckedDiv for Complex<T> { | ||
| #[inline] | ||
| fn checked_div(&self, other: &Self) -> Option<Self> { | ||
| let norm_sqr = other | ||
| .re | ||
| .checked_mul(&other.re)? | ||
| .checked_add(&other.im.checked_mul(&other.im)?)?; | ||
| let re = self | ||
| .re | ||
| .checked_mul(&other.re)? | ||
| .checked_add(&self.im.checked_mul(&other.im)?)?; | ||
| let im = self | ||
| .im | ||
| .checked_mul(&other.re)? | ||
| .checked_sub(&self.re.checked_mul(&other.im)?)?; | ||
| Some(Self::new( | ||
| re.checked_div(&norm_sqr)?, | ||
| im.checked_div(&norm_sqr)?, | ||
| )) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
IMHO I find it far easier to read if one uses aliases for the real/imag parts as in the formula of the documentation block above, e.g.
let(a, b) = (&self.re,&self.im);let(c, d) = (&other.re,&other.im);let norm_sqr = c.checked_mul(c)?.checked_add(&d.checked_mul(d)?)?;
...Inconsistency to other code sections needs to be weighted in though...
There was a problem hiding this comment.
Nowhere else in the arithmetic code does this as far as I can tell.
Uh oh!
There was an error while loading. Please reload this page.
| } | ||
| impl<T: Clone + Num + CheckedAdd + CheckedSub + CheckedMul + CheckedDiv + CheckedRem> Complex<T> { | ||
| fn checked_div_trunc(&self, divisor: &Self) -> Option<Self> { |
There was a problem hiding this comment.
It parallels the implementation for Rem, which has its own private method div_trunc which is right above it and right beside the Rem impl. I don't believe it's specifically noteworthy to merit being added to the PR description.
Implements the
Checked[Add,Sub,Mul,Div,Rem]traits fromnum_traits.