Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add finv() and fdiv() #41

Merged
merged 1 commit into from
Mar 28, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,62 @@ impl<T: Clone + Float> Complex<T> {
}
((one + self).ln() - (one - self).ln()) / two
}

/// Returns `1/self` using floating-point operations.
///
/// This may be more accurate than the generic `self.inv()` in cases
/// where `self.norm_sqr()` would overflow to ∞ or underflow to 0.
///
/// # Examples
///
/// ```
/// use num_complex::Complex64;
/// let c = Complex64::new(1e300, 1e300);
///
/// // The generic `inv()` will overflow.
/// assert!(!c.inv().is_normal());
///
/// // But we can do better for `Float` types.
/// let inv = c.finv();
/// assert!(inv.is_normal());
/// println!("{:e}", inv);
///
/// let expected = Complex64::new(5e-301, -5e-301);
/// assert!((inv - expected).norm() < 1e-315);
/// ```
#[inline]
pub fn finv(&self) -> Complex<T> {
let norm = self.norm();
self.conj() / norm / norm
}

/// Returns `self/other` using floating-point operations.
///
/// This may be more accurate than the generic `Div` implementation in cases
/// where `other.norm_sqr()` would overflow to ∞ or underflow to 0.
///
/// # Examples
///
/// ```
/// use num_complex::Complex64;
/// let a = Complex64::new(2.0, 3.0);
/// let b = Complex64::new(1e300, 1e300);
///
/// // Generic division will overflow.
/// assert!(!(a / b).is_normal());
///
/// // But we can do better for `Float` types.
/// let quotient = a.fdiv(b);
/// assert!(quotient.is_normal());
/// println!("{:e}", quotient);
///
/// let expected = Complex64::new(2.5e-300, 5e-301);
/// assert!((quotient - expected).norm() < 1e-315);
/// ```
#[inline]
pub fn fdiv(&self, other: Complex<T>) -> Complex<T> {
self * other.finv()
}
}

impl<T: Clone + FloatCore> Complex<T> {
Expand Down