Cライブラリ関数 -log10()
説明
Cライブラリ関数double log10(double x)返しますxの常用対数(底を10とする対数)。
log10()C標準ライブラリです<math.h>中の関数で、浮動小数点数の常用対数(底を10とする)を計算するために使用されます。これは一般的な数学関数であり、科学計算、工学、金融などの分野で広く応用されています。
宣言
以下は log10() 関数の宣言です。
#include <math.h> double log10(double x); float log10f(float x); long double log10l(long double x);
パラメータ
x:入力する浮動小数点数であり、正の数(0より大きい)でなければなりません。
戻り値
- 返します
xの常用対数、もしxが負またはゼロの場合、定義域エラーまたは範囲エラーが発生します。
エラー処理
- もし
xが負の場合、log10()関数は NaN を返し、設定しますerrnoためにEDOM。 - もし
xがゼロの場合、log10()関数は返します-HUGE_VAL(負の無限大)、そして設定しますerrnoためにERANGE。
例
以下の例は、log10() 関数の使用方法を示しています。
例
#include <stdio.h>
#include <math.h>
int main ()
{
double x, ret;
x = 10000;
/* log10(10000) を計算する */
ret = log10(x);
printf("log10(%lf) = %lf\n", x, ret);
return(0);
}
#include <math.h>
int main ()
{
double x, ret;
x = 10000;
/* log10(10000) を計算する */
ret = log10(x);
printf("log10(%lf) = %lf\n", x, ret);
return(0);
}
上記のプログラムをコンパイルして実行してみましょう。これにより次の結果が生成されます:
log10(10000.000000) = 4.000000
複数の値の対数を処理する
次の例は、複数の値の対数を処理する方法を示しています:
例
#include <stdio.h>
#include <math.h>
#include <errno.h>
int main() {
double values[] = {1.0, 10.0, 100.0, -1.0, 0.0};
int num_values = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < num_values; i++) {
double x = values[i];
errno = 0; // errno をリセットする
double result = log10(x);
if (errno == EDOM) {
printf("Domain error: log10(%f) is not defined\n", x);
} else if (errno == ERANGE) {
printf("Range error: log10(%f) results in an overflow or underflow\n", x);
} else {
printf("log10(%f) = %f\n", x, result);
}
}
return 0;
}
#include <math.h>
#include <errno.h>
int main() {
double values[] = {1.0, 10.0, 100.0, -1.0, 0.0};
int num_values = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < num_values; i++) {
double x = values[i];
errno = 0; // errno をリセットする
double result = log10(x);
if (errno == EDOM) {
printf("Domain error: log10(%f) is not defined\n", x);
} else if (errno == ERANGE) {
printf("Range error: log10(%f) results in an overflow or underflow\n", x);
} else {
printf("log10(%f) = %f\n", x, result);
}
}
return 0;
}
上記のプログラムをコンパイルして実行してみましょう。これにより次の結果が生成されます:
log10(1.000000) = 0.000000 log10(10.000000) = 1.000000 log10(100.000000) = 2.000000 log10(-1.000000) = nan log10(0.000000) = -inf
コード解析
- 複数の浮動小数点数を含む配列を定義します
values。 - 使用して
forループで各値を走査し、呼び出しますlog10(x)計算を行います。 - リセット
errnoを 0 にして、可能性のあるエラーを確認します。 - 各値の対数計算結果、またはエラーメッセージを出力します。
使用シナリオ
log10()関数は多くのアプリケーションで幅広い用途があり、以下を含みますがこれらに限定されません:
- 常用対数を計算して桁(オーダー)の変化を処理します。
- 対数スケールのデータを分析します。
- 常用対数方程式を含む数学的問題を解決します。
- 金融において対数収益率や対数価格変化を計算します。
まとめ
log10()関数は浮動小数点数の常用対数を計算するために使用され、常用対数演算を処理するための重要なツールです。適切に使用することでlog10()、科学計算、金融、工学アプリケーションで対数演算を実現し、潜在的なエラーケースを適切に処理することができます。
C標準ライブラリ - <math.h>