Skip to content

Commit

Permalink
cmath (tgamma): lgamma を使うべき場合について記述
Browse files Browse the repository at this point in the history
  • Loading branch information
akinomyoga committed Feb 9, 2025
1 parent 7f763a4 commit 932634a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion reference/cmath/lgamma.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ namespace std {
- `x = -∞` の場合、戻り値は `+∞` となる。
- `x = +∞` の場合、戻り値は `+∞` となる。
- C++23では、(1)、(2)、(3)が(4)に統合され、拡張浮動小数点数型を含む浮動小数点数型へのオーバーロードとして定義された
- この関数はガンマ関数 ([`tgamma`](tgamma.md)) がオーバーフローするような場合に使う。
具体例については[ガンマ関数の備考](tgamma.md#remarks-lgamma)を参照のこと。
## 例
```cpp example
Expand Down
26 changes: 26 additions & 0 deletions reference/cmath/tgamma.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,32 @@ $$ \Gamma (x) = \int_0^\infty t^{x-1} e^{-t} dt $$
- `gamma` という関数は既にあったが処理系によって定義が違ったため、本当の (true) ガンマ関数 `tgamma` と名付けられた。
- C++23では、(1)、(2)、(3)が(4)に統合され、拡張浮動小数点数型を含む浮動小数点数型へのオーバーロードとして定義された
### <a id="remarks-lgamma" href="#remarks-lgamma">lgamma との使い分け</a>
ガンマ関数は急激に増加し容易にオーバーフローするので、代わりにガンマ関数の結果を自然対数で返す関数 [`lgamma`](lgamma.md) を用いた方が良いことが多くある。
例えばガンマ関数の比を計算する場合には、 ガンマ関数の対数の差を取ってから指数関数 [`std::exp`](exp.md) を適用するのが賢明である。
$$ \frac{\Gamma(2026)}{\Gamma(2025)} = \exp[\ln\Gamma(2026) - \ln\Gamma(2025)] $$
```cpp example
#include <cmath>
#include <iostream>
int main() {
std::cout << std::tgamma(2026.0) / std::tgamma(2025.0) << std::endl;
std::cout << std::exp(std::lgamma(2026.0) - std::lgamma(2025.0)) << std::endl;
}
```
* std::tgamma[color ff0000]
* std::lgamma[color 0000ff][link lgamma.md]

出力例
```
-nan
2025
```

上の結果では、直接ガンマ関数を計算した場合はオーバーフローによって inf / inf となり最終結果が -nan になっているが、`lgamma` を使った場合には正しい値が計算できている。
ただし、`lgamma` は飽くまでガンマ関数の「絶対値」の対数であることに注意する。
ガンマ関数の引数が負になる場合はガンマ関数が負の値を取りうるので符号は別に求める必要がある。

##
```cpp example
Expand Down

0 comments on commit 932634a

Please sign in to comment.