|
| 1 | +//! Conversions between rectangular (Cartesian) and polar coordinate systems. |
| 2 | +//! |
| 3 | +//! This module provides utilities for converting rectangular coordinates |
| 4 | +//! into polar coordinates with angles expressed in degrees. |
| 5 | +//! |
| 6 | +//! More information: <https://en.wikipedia.org/wiki/Polar_coordinate_system> |
| 7 | +
|
| 8 | +/// Convert rectangular (Cartesian) coordinates to polar coordinates. |
| 9 | +/// |
| 10 | +/// The returned tuple contains: |
| 11 | +/// - magnitude (r) |
| 12 | +/// - angle (θ) in degrees |
| 13 | +/// |
| 14 | +/// Both values are rounded to 2 decimal places. |
| 15 | +/// |
| 16 | +/// # Formula |
| 17 | +/// - r = sqrt(x² + y²) |
| 18 | +/// - θ = atan2(y, x) converted to degrees |
| 19 | +pub fn rectangular_to_polar(real: f64, imag: f64) -> (f64, f64) { |
| 20 | + let magnitude = (real.powi(2) + imag.powi(2)).sqrt(); |
| 21 | + let angle = imag.atan2(real).to_degrees(); |
| 22 | + |
| 23 | + ( |
| 24 | + round_to_two_decimals(magnitude), |
| 25 | + round_to_two_decimals(angle), |
| 26 | + ) |
| 27 | +} |
| 28 | + |
| 29 | +fn round_to_two_decimals(value: f64) -> f64 { |
| 30 | + (value * 100.0).round() / 100.0 |
| 31 | +} |
| 32 | + |
| 33 | +#[cfg(test)] |
| 34 | +mod tests { |
| 35 | + use super::*; |
| 36 | + |
| 37 | + #[test] |
| 38 | + fn test_rectangular_to_polar() { |
| 39 | + assert_eq!(rectangular_to_polar(5.0, -5.0), (7.07, -45.0)); |
| 40 | + assert_eq!(rectangular_to_polar(-1.0, 1.0), (1.41, 135.0)); |
| 41 | + assert_eq!(rectangular_to_polar(-1.0, -1.0), (1.41, -135.0)); |
| 42 | + assert_eq!(rectangular_to_polar(1e-10, 1e-10), (0.0, 45.0)); |
| 43 | + assert_eq!(rectangular_to_polar(-1e-10, 1e-10), (0.0, 135.0)); |
| 44 | + assert_eq!(rectangular_to_polar(9.75, 5.93), (11.41, 31.31)); |
| 45 | + assert_eq!(rectangular_to_polar(10000.0, 99999.0), (100497.76, 84.29)); |
| 46 | + } |
| 47 | +} |
0 commit comments