Complex Numbers
Recipe | Crates | Categories |
---|---|---|
Create Complex Numbers | ||
Add Complex Numbers | ||
Use Mathematical Functions on Complex Numbers |
Create 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.
/// Creates complex numbers with integer and floating-point components. fn main() { // Create a complex number with integer components. let complex_integer = num::complex::Complex::new(10, 20); // Create a complex number with floating-point components. let complex_float = num::complex::Complex::new(10.1, 20.1); println!("Complex integer: {}", complex_integer); println!("Complex float: {}", complex_float); }
Add 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).
//! Demonstrates the manipluation of complex numbers. fn main() { // Create two complex numbers. let complex_num1 = num::complex::Complex::new(10.0, 20.0); let complex_num2 = num::complex::Complex::new(3.1, -4.2); // Add the two complex numbers. let sum = complex_num1 + complex_num2; println!("Sum: {}", sum); }
Use Mathematical Functions on Complex Numbers
Complex numbers have a range of interesting properties when it comes to how they interact with other mathematical functions, most notably 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
⮳.
use std::f64::consts::PI; use num::complex::Complex; /// This example shows how to use the `exp` function on a complex number. fn main() { let x = Complex::new(0.0, 2.0 * PI); println!("e^(2i * pi) = {}", x.exp()); // =~1 }