Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add Sine function (TheAlgorithms#437)
  • Loading branch information
zefr0x authored Jan 6, 2023
commit 39b747f6c599883cc361c5d994e7da6000f3de6c
2 changes: 2 additions & 0 deletions src/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mod random;
mod sieve_of_eratosthenes;
mod signum;
mod simpson_integration;
mod sine;
mod square_root;
mod trial_division;
mod zellers_congruence_algorithm;
Expand Down Expand Up @@ -82,6 +83,7 @@ pub use self::random::PCG32;
pub use self::sieve_of_eratosthenes::sieve_of_eratosthenes;
pub use self::signum::signum;
pub use self::simpson_integration::simpson_integration;
pub use self::sine::sine;
pub use self::square_root::{fast_inv_sqrt, square_root};
pub use self::trial_division::trial_division;
pub use self::zellers_congruence_algorithm::zellers_congruence_algorithm;
58 changes: 58 additions & 0 deletions src/math/sine.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
}
}