forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sine.rs
58 lines (48 loc) · 1.49 KB
/
sine.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Calculate Sine function.
// Formula: sine(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
// Where: x = angle in randians.
// It is not a real function so I will just do 9 loops, it's just an approximation.
// Source:
// https://web.archive.org/web/20221111013039/https://www.homeschoolmath.net/teaching/sine_calculator.php
use std::f32::consts::PI;
fn factorial(num: u64) -> u64 {
(1..=num).product()
}
pub fn sine(angle: f64) -> f64 {
// Simplify the angle
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) {
// I will round the result to 3 decimal places, since it's an approximation.
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);
}
}