Skip to content

Instantly share code, notes, and snippets.

@sarmadgulzar
Created June 6, 2021 04:35
Show Gist options
  • Save sarmadgulzar/8ca81eb1365e5ceb71727238f4ade3e4 to your computer and use it in GitHub Desktop.
Save sarmadgulzar/8ca81eb1365e5ceb71727238f4ade3e4 to your computer and use it in GitHub Desktop.
Complex Numbers in Rust
use std::fmt;
use std::ops;
#[derive(Copy, Clone)]
pub struct Complex {
pub real: f64,
pub imag: f64,
}
impl Complex {
pub fn conjugate(&self) -> Self {
Self {
real: self.real,
imag: -self.imag,
}
}
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.imag >= 0.0 {
write!(f, "{:.2}+{:.2}i", self.real, self.imag)
} else {
write!(f, "{:.2}{:.2}i", self.real, self.imag)
}
}
}
impl ops::Add for Complex {
type Output = Self;
fn add(self, other: Self) -> Self {
return Self {
real: self.real + other.real,
imag: self.imag + other.imag,
};
}
}
impl ops::Div for Complex {
type Output = Self;
fn div(self, other: Self) -> Self {
let denominator_conjugate = other.conjugate();
let numerator = self * denominator_conjugate;
let denominator = other * denominator_conjugate;
return Self {
real: numerator.real / denominator.real,
imag: numerator.imag / denominator.real,
};
}
}
impl ops::Mul for Complex {
type Output = Self;
fn mul(self, other: Self) -> Self {
return Self {
real: (self.real * other.real - self.imag * other.imag),
imag: (self.real * other.imag + self.imag * other.real),
};
}
}
impl ops::Sub for Complex {
type Output = Self;
fn sub(self, other: Self) -> Self {
return Self {
real: self.real - other.real,
imag: self.imag - other.imag,
};
}
}
mod complex;
use complex::Complex;
fn main() {
let c1 = Complex {
real: 5.0,
imag: -6.0,
};
let c2 = Complex {
real: -7.0,
imag: 8.0,
};
println!("c1 + c2 = {}", c1 + c2); // c1 + c2 = -2.00+2.00i
println!("c1 - c2 = {}", c1 - c2); // c1 - c2 = 12.00-14.00i
println!("c1 * c2 = {}", c1 * c2); // c1 * c2 = 13.00+82.00i
println!("c1 / c2 = {}", c1 / c2); // c1 / c2 = -0.73+0.02i
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment