Python, JavaScript 및 Perl에서 삼각 함수를 계산하는 프로그램(Maclaurin 시리즈 포함)

원래 출판here at xtrp.io, 컴퓨터 과학 및 거의 모든 프로그래밍에 대한 제 블로그입니다.

소개



컴퓨터가 나눗셈과 같은 특정 수학 함수 또는 사인이나 코사인과 같은 삼각 함수를 어떻게 계산하는지 궁금한 적이 있습니까? 글쎄, 이러한 수학 함수 중 일부에는 매우 정확한 결과를 매우 쉽게 계산하는 유용한 공식이 있습니다. 사인과 코사인의 경우 일반적으로 사용되는 공식은 다음과 같습니다.



그리고 코사인의 경우:



각 함수의 입력은 각도가 아니라 라디안입니다.

두 수식에 사용된 급수는 Maclaurin series(Taylor series의 한 유형)이라고 하며 급수 확장을 통해 사인 및 코사인 함수에서 파생될 수 있습니다.

프로그램 작동 방식



Python, JavaScript 및 Perl의 세 가지 주요 스크립팅 언어로 이 두 계산을 구현하는 프로그램을 작성했습니다. 이러한 프로그램에는 경우에 따라 내장 π 상수를 사용하는 것을 제외하고 내장 삼각 함수 또는 기타 유틸리티가 포함되어 있지 않습니다. 모든 코드는 CC0 라이센스입니다.

내가 사용한 접근 방식은 computeSeries라는 일반화된 함수를 생성합니다. 이 함수는 x를 사인 또는 코사인을 계산하는 숫자로, 계열의 시작 숫자(사인의 경우 x, 코사인의 경우 1), 지수 및 계승 밑을 급수의 첫 번째 항(사인의 경우 3, 코사인의 경우 2).

각 계열을 계산할 때 상당히 정확한 결과를 얻기 위해 계열의 약 10개 용어만 필요하다는 것을 알았습니다.

프로그램에는 도 단위의 사인 및 코사인 함수에 대한 유틸리티 함수가 추가로 포함됩니다. 각 프로그램의 끝 부분에는 예상대로 작동하는 각 기능에 대한 몇 가지 테스트도 포함됩니다.

파이썬에서



부담없이 view the below code as a GitHub Gist .

from math import pi

# round a number (x) to nearest 10 digits
def rounded(x):
    return round(x, 10)

# get the factorial of a number (x)
# factorial(x) is the product of every number from 1 to N inclusive
def factorial(x):
    n = 1; # n is the result
    # multiply n by every number from 1 to x inclusive
    for i in range(2, x + 1):
        n *= i
    return n

""" get the result of the cos and sin formulas
    where the functions are sin(x radians) or cos(x radians),
    n is the start value (n = x for sin, n = 1 for cos), and
    i_start is the exponent and factorial base in the first term """
def computeSeries(x, n, i_start):
    iterations = 20 # iterations is twice the amount of terms to use
    multiplier = 1
    for i in range(i_start, i_start + iterations, 2): # i increases by 2 each term
        multiplier *= -1 # alternates between addition and subtraction each term
        next_term = (x**i) / factorial(i) # each term is (x^i) / i!
        n += multiplier * next_term # add or subtract from final result
    return n

# get sin of x radians
def sin(x):
    return rounded(computeSeries(x, x, 3))

# get cos of x radians
def cos(x):
    return rounded(computeSeries(x, 1, 2))

# get sin of x degrees
def sinDeg(x):
    return sin(x * pi / 180)

# get cos of x degrees
def cosDeg(x):
    return cos(x * pi / 180)

# test the functions
print(sin(pi / 6)); # 0.5
print(sinDeg(45)); # 0.7071
print(sinDeg(52)); # 0.78801

print(cos(pi / 3)); # 0.5
print(cosDeg(45)); # 0.7071
print(cosDeg(52)); # 0.615661


자바스크립트에서



부담없이 view the below code as a GitHub Gist .

// round a number (x) to nearest 10 digits
const rounded = (x) => {
    return parseFloat(x.toFixed(10));
}

// get the factorial of a number (x)
// factorial(x) is the product of every number from 1 to x inclusive
const factorial = (x) => {
    let n = 1; // n is the result
    // multiply n by every number from 1 to x inclusive
    for(let i = 2; i <= x; i++) {
        n *= i;
    }
    return n;
}

/* get the result of the cos and sin formulas
   where the functions are sin(x radians) or cos(x radians),
   n is the start value (x for sin, 1 for cos), and i_start
   is the exponent and factorial base in the first term */
const computeSeries = (x, n, i_start) => {
    const iterations = 20; // iterations is twice the amount of terms to use
    let multiplier = 1;
    let i = i_start;
    while(i < i_start + iterations) {
        multiplier *= -1; // alternates between addition and subtraction each iteration
        const next_term = (x**i) / factorial(i); // each term is (x^i) / i!
        n += multiplier * next_term // add or subtract from final result
        i += 2 // i increases by 2 each term
    }
    return n
}

// get sin of x radians
const sin = (x) => {
    return rounded(computeSeries(x, x, 3));
}
// get cos of x radians
const cos = (x) => {
    return rounded(computeSeries(x, 1, 2));
}
// get sin of x degrees
const sinDeg = (x) => {
    return sin(x * Math.PI / 180);
}
// get cos of x degrees
const cosDeg = (x) => {
    return cos(x * Math.PI / 180);
}

// test the functions
console.log(sin(Math.PI / 6)); // 0.5
console.log(sinDeg(45)); // 0.7071
console.log(sinDeg(52)); // 0.78801

console.log(cos(Math.PI / 3)); // 0.5
console.log(cosDeg(45)); // 0.7071
console.log(cosDeg(52)); // 0.615661


펄에서



부담없이 view the below code as a GitHub Gist .

#!/usr/bin/perl
use warnings;

$pi = 3.14159265358979323;

# get the factorial of a number (x)
# factorial(x) is the product of every number from 1 to N inclusive
sub factorial {
    my ($x) = @_;
    my $n = 1; # n is the result
    # multiply n by every number from 1 to x inclusive
    my @nums_to_multiply = (1..$x);
    for(@nums_to_multiply){
        $n *= $_;
    }
    return $n;
}

=begin
get the result of the cos and sin formulas
where the functions are sin(x radians) or cos(x radians),
n is the start value (n = x for sin, n = 1 for cos), and
i_start is the exponent and factorial base in the first term
=cut
sub computeSeries {
    $ITERATIONS = 20; # iterations is twice the amount of terms to use
    my ($x, $n, $i_start) = @_;
    my $multiplier = 1;
    $i = $i_start;
    while($i < $i_start + $ITERATIONS) {
        $multiplier *= -1; # alternates between addition and subtraction each term
        $n += $multiplier * (($x**$i) / factorial($i)); # add or subtract ((x^i) / i!) from final result
        $i += 2; # i increases by 2 each term
    }
    return $n;
}

# get sin of x radians
sub mySin {
    my ($x) = @_;
    return computeSeries($x, $x, 3);
}
# get cos of x radians
sub myCos {
    my ($x) = @_;
    return computeSeries($x, 1, 2);
}
# get sin of x degrees
sub sinDeg {
    my ($x) = @_;
    return mySin($x * $pi / 180);
}
# get cos of x degrees
sub cosDeg {
    my ($x) = @_;
    return myCos($x * $pi / 180);
}

# test the functions
print(sin($pi / 6) . "\n"); # 0.5
print(sinDeg(45)   . "\n"); # 0.7071
print(sinDeg(52)   . "\n"); # 0.78801

print(cos($pi / 3) . "\n"); # 0.5
print(cosDeg(45)   . "\n"); # 0.7071
print(cosDeg(52)   . "\n"); # 0.615661


결론



이것이 컴퓨터와 언어가 사인 및 코사인과 같은 삼각 함수를 계산하는 방법을 이해하는 데 도움이 되기를 바랍니다. 삼각 함수를 계산하는 데 사용되는 수학 공식이 정확히 어떻게 유도되는지 자세히 알아보려면 Khan Academy의 the videos on Taylor and Maclaurin series을 살펴보는 것이 좋습니다.

이러한 프로그램은 모두 CC0 라이선스에 따라 라이선스가 부여되므로 귀속 없이 원하는 대로 코드를 자유롭게 사용할 수 있습니다.

스크롤해주셔서 감사합니다.

이 게시물의 출처는 my blog at xtrp.io 입니다.

— 가브리엘 로무알도, 2020년 12월 31일

좋은 웹페이지 즐겨찾기