f-office-units 0.2.2

Integer lengths and unit conversions for F-Office.
Documentation
use super::{FULL_TURN, HALF_TURN, ONE, QUARTER_TURN, UNIT, angle_of, root, rounded, sin_cos};

/// An angle of whole 60,000ths of a degree as a value.
fn degrees_60000(angle: i128) -> i128 {
    angle * ONE
}

/// √2/2 and √3/2 in units of 2^-62, rounded.
const HALF_ROOT_2: i128 = 3_260_954_456_333_195_553;
const HALF_ROOT_3: i128 = 3_993_837_246_235_628_775;

fn near(a: i128, b: i128, within: i128) -> bool {
    (a - b).abs() <= within
}

#[test]
fn rounds_to_the_nearest_and_a_half_away_from_zero() {
    for (dividend, divisor, quotient) in [
        (7, 2, 4),
        (-7, 2, -4),
        (7, -2, -4),
        (5, 3, 2),
        (4, 3, 1),
        (-4, 3, -1),
        (9, 0, 0),
    ] {
        assert_eq!(rounded(dividend, divisor), quotient, "{dividend} {divisor}");
    }
    assert_eq!(root(17), 4);
}

#[test]
fn gives_the_sine_and_cosine_of_the_angles_whose_values_are_known() {
    let half = UNIT / 2;
    for (angle, sin, cos) in [
        (0, 0, UNIT),
        (1_800_000, half, HALF_ROOT_3),
        (2_700_000, HALF_ROOT_2, HALF_ROOT_2),
        (3_600_000, HALF_ROOT_3, half),
        (5_400_000, UNIT, 0),
        (12_600_000, -half, -HALF_ROOT_3),
        (18_900_000, -HALF_ROOT_2, HALF_ROOT_2),
        (-5_400_000, -UNIT, 0),
        (21_600_000 * 3 + 1_800_000, half, HALF_ROOT_3),
    ] {
        let [s, c] = sin_cos(degrees_60000(angle));
        assert!(near(s, sin, 64), "{angle}: {s}");
        assert!(near(c, cos, 64), "{angle}: {c}");
    }
}

#[test]
fn keeps_the_sum_of_the_squares_of_sine_and_cosine_at_one() {
    for step in 0..=720_i128 {
        let [s, c] = sin_cos(step * FULL_TURN / 720 + 12_345);
        // A unit of the squares is 2^-62 × 2^-62.
        let sum = s * s / UNIT + c * c / UNIT;
        assert!(near(sum, UNIT, 256), "{step}: {sum}");
    }
}

#[test]
fn gives_the_angle_of_a_point_in_its_own_quarter() {
    for (x, y, angle) in [
        (0, 0, 0),
        (5, 0, 0),
        (-5, 0, HALF_TURN),
        (0, 5, QUARTER_TURN),
        (0, -5, -QUARTER_TURN),
    ] {
        assert_eq!(angle_of(x, y), angle, "{x} {y}");
    }
    for (x, y, angle) in [
        (7, 7, 2_700_000),
        (-7, -7, -8_100_000),
        (HALF_ROOT_3, UNIT / 2, 1_800_000),
        (-UNIT / 2, HALF_ROOT_3, 7_200_000),
        // A point far from the origin and one close to it.
        (1 << 120, 1 << 120, 2_700_000),
        (1, -1, -2_700_000),
    ] {
        assert!(near(angle_of(x, y), degrees_60000(angle), 1), "{x} {y}");
    }
}

#[test]
fn gives_back_the_angle_of_its_own_sine_and_cosine() {
    for step in 0..720_i128 {
        let angle = step * FULL_TURN / 720 - HALF_TURN + 1;
        let [s, c] = sin_cos(angle);
        assert!(near(angle_of(c, s), angle, 2), "{step}");
    }
}