Skip to content

Instantly share code, notes, and snippets.

@kamikat
Last active December 7, 2023 12:50
Show Gist options
  • Save kamikat/c4d472ce3c61feec6376 to your computer and use it in GitHub Desktop.
Save kamikat/c4d472ce3c61feec6376 to your computer and use it in GitHub Desktop.
SCSS/SASS module calculating sin/cos/tan using Taylor Expansion.
///////////////////////////////////////////////////////////
// Plain SASS Trigonometry Algorithm in Taylor Expansion //
// //
// Based on //
// http://japborst.net/posts/sass-sines-and-cosines //
///////////////////////////////////////////////////////////
$pi: 3.14159265359;
$_precision: 10;
@function pow($base, $exp) {
$value: $base;
@if $exp > 1 {
@for $i from 2 through $exp {
$value: $value * $base;
}
}
@if $exp < 1{
@for $i from 0 through -$exp {
$value: $value / $base;
}
}
@return $value;
}
@function fact($num) {
$fact: 1;
@if $num > 0{
@for $i from 1 through $num {
$fact: $fact * $i;
}
}
@return $fact;
}
@function _to_unitless_rad($angle) {
@if unit($angle) == "deg" {
$angle: $angle / 180deg * $pi;
}
@if unit($angle) == "rad" {
$angle: $angle / 1rad;
}
@return $angle;
}
@function sin($angle){
$a: _to_unitless_rad($angle);
$sin: $a;
@for $n from 1 through $_precision {
$sin: $sin + (pow(-1, $n) / fact(2 * $n + 1) ) * pow($a, (2 * $n + 1));
}
@return $sin;
}
@function cos($angle){
$a: _to_unitless_rad($angle);
$cos: 1;
@for $n from 1 through $_precision {
$cos: $cos + ( pow(-1,$n) / fact(2*$n) ) * pow($a,2*$n);
}
@return $cos;
}
@function tan($angle){
@return sin($angle) / cos($angle);
}
@lafnian1990
Copy link

lafnian1990 commented Aug 6, 2021

Thanks for the detailed code review, I was looking for this solution. I was looking for several options for solving trigonometric equations. I have tried using online calculators but these programs do not show the progress of the solution and the internal code. I realized that the best way to understand logic https://plainmath.net/secondary/geometry/trigonometry is to learn the dynamic manual process of solving trigonometric equations. Such resources help build the right understanding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment