use std::f32::consts::PI;
fn factorial(num: u64) -> u64 {
(1..=num).product()
}
pub fn sine(angle: f64) -> f64 {
let angle = angle % (2.0 * PI as f64);
let mut result = angle;
let mut a: u64 = 3;
let mut b = -1.0;
for _ in 0..9 {
result += b * (angle.powi(a as i32)) / (factorial(a) as f64);
b = -b;
a += 2;
}
result
}
#[cfg(test)]
mod tests {
use super::{sine, PI};
fn assert(angle: f64, expected_result: f64) {
assert_eq!(
format!("{:.3}", sine(angle)),
format!("{:.3}", expected_result)
);
}
#[test]
fn test_sine() {
assert(0.0, 0.0);
assert(PI as f64 / 2.0, 1.0);
assert(PI as f64 / 4.0, 1.0 / f64::sqrt(2.0));
assert(PI as f64, -0.0);
assert(PI as f64 * 3.0 / 2.0, -1.0);
assert(PI as f64 * 2.0, 0.0);
assert(PI as f64 * 2.0 * 3.0, 0.0);
assert(-PI as f64, 0.0);
assert(-PI as f64 / 2.0, -1.0);
assert(PI as f64 * 8.0 / 45.0, 0.5299192642);
assert(0.5, 0.4794255386);
}
}