私が気にする100の事象

気にしなければ始まらない。

cos関数

概要

C言語でコサイン値を計算する関数です。 <math.h>#includeすることによって使うことができます。

定義

定義は次の通りになります。

double cos(double)
機能 内容
第1引数 double 任意のラジアンx
返り値 double 余弦cos(x)

仕様

ISO/IEC 9899:1999 における仕様を示します。

7.12.4.5 The cos functions
Synopsis
1 #include <math.h> double cos(double x);
float cosf(float x);
long double cosl(long double x);
Description
2 The cos functions compute the cosine of x (measured in radians).
Returns
3 The cos functions return cos x.

また、JIS X 3010:2003 における仕様を示します。

7.12.4.5 cos 関数群
形式 #include <math.h>
double cos(double x);
float cosf(float x);
long double cosl(long double x);
機能 cos 関数群は,x(ラジアン値)の余弦を計算する。
返却値 cos 関数群は,余弦値を返す。

使用例

#include <stdio.h>
#include <math.h>

#define PI 3.14159265358979323846

int main() {
    printf("%lf\n", cos(0.0));
    printf("%lf\n", cos(PI / 6.0));
    printf("%lf\n", cos(PI / 4.0));
    printf("%lf\n", cos(PI / 3.0));
    printf("%lf\n", cos(PI / 2.0));
    printf("%lf\n", cos(PI));
    return 0;
}

結果は以下のようになります。
コンパイラEmbarcadero C++ 7.20です。

./cos.exe
1.000000
0.866025
0.707107
0.500000
0.000000
-1.000000

実装例

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

double cos(double x) {
    double sum = 1, k = 1;
    int i;
    x -= (int)(x / (2 * M_PI)) * 2 * M_PI;
    for (i = 1;; i += 2) {
        k *= -(x * x) / (i * (i + 1));
        if (sum == sum + k) return sum;
        else sum += k;
    }
}

マクローリン展開を用いて実装することができるはずです。多分。
以下の図は0.000244140625ごとにxの値を変えたときのfor文の中身の実行回数です。
なお、for文の繰り返し回数は27回以内に収まるようです。

f:id:skytomo:20180513213517p:plain
cos関数における収束回数
cos関数のマクローリン展開は以下の記事を参考にするといいです。

関連記事

100-matters.hatenablog.jp

最終更新日: 2018-05-19