Complex numbers
Add the num-complex
create to your own project:
cargo add num-complex
Creating complex numbers
Creates complex numbers of type num_complex::Complex
. Both the real and
imaginary part of the complex number must be of the same type.
use num_complex::Complex; fn main() { let complex_integer = Complex::new(10, 20); let complex_float = Complex::new(10.1, 20.1); println!("Complex integer: {}", complex_integer); println!("Complex float: {}", complex_float); }
Adding complex numbers
Performing mathematical operations on complex numbers is the same as on built in types: the numbers in question must be of the same type (i.e. floats or integers).
use num_complex::Complex; fn main() { let complex_num1 = Complex::new(10.0, 20.0); // Compiler will infer numeric type f32. let complex_num2 = Complex::new(3.1, -4.2_f32); // Numeric type can also be specified explicitly. let sum = complex_num1 + complex_num2; println!("Sum: {}", sum); }
Mathematical functions
Complex numbers have a range of interesting properties when it comes to
how they interact with other mathematical functions, most notibly the family
of sine functions as well as the number e. To use these functions with
complex numbers, the Complex type has a few built in
functions, all of which can be found here: num_complex::Complex
.
See also: Euler's Identity
use std::f64::consts::PI; use num_complex::Complex; fn main() { let x = Complex::new(0.0, 2.0*PI); println!("e^(2i * pi) = {}", x.exp()); // =~1 }