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 complex power (.powc()) for T: float. #106

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 14 additions & 0 deletions src/complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,18 @@ impl<T: Clone + Float + Num> Complex<T> {
pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
Complex::new(*r * theta.cos(), *r * theta.sin())
}

/// Raises self to a complex power `exp`
#[inline]
pub fn powc(&self, exp: &Complex<T>) -> Complex<T> {
// Formula: (r e^(ti))^(a+bi) = (r^a e^(-bt)) e^((ln(r)b+at)i)
let (r, t) = exp.to_polar();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self is the base that should be made polar, not exp.


let r2 = r.powf(exp.re) * (-exp.im * t).exp();
let t2 = r.ln() * self.im + self.re * t;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

t2 needs to be computed from exp.im and exp.re, not from self.


Self::from_polar(&r2, &t2)
}
}

macro_rules! forward_val_val_binop {
Expand Down Expand Up @@ -402,6 +414,7 @@ mod test {
assert_eq!(_1_0i * c, c);
}
}

#[test]
fn test_div() {
assert_eq!(_neg1_1i / _0_1i, _1_1i);
Expand All @@ -411,6 +424,7 @@ mod test {
}
}
}

#[test]
fn test_neg() {
assert_eq!(-_1_0i + _0_1i, _neg1_1i);
Expand Down