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 b506105 commit e1febaf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions reference/cmath/lgamma.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ namespace std {
- `x = +∞` の場合、戻り値は `+∞` となる。
- C++23では、(1)、(2)、(3)が(4)に統合され、拡張浮動小数点数型を含む浮動小数点数型へのオーバーロードとして定義された
この関数はガンマ関数 ([`tgamma`](tgamma.md)) がオーバーフローするような場合に使う。
具体例については[ガンマ関数の備考](tgamma.md#remarks-lgamma)を参照のこと。
## 例
```cpp example
Expand Down
25 changes: 25 additions & 0 deletions reference/cmath/tgamma.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,31 @@ $$ \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(102)}{\Gamma(100)} = \exp[\ln\Gamma(102) - \ln\Gamma(100)] $$
```cpp example
#include <cmath>
#include <iostream>
int main() {
std::cout << std::tgamma(2023.0) / std::tgamma(2022.0) << std::endl;
std::cout << std::exp(std::lgamma(2023.0) - std::lgamma(2022.0)) << std::endl;
}
```
* std::tgamma[color ff0000]
* std::lgamma[color 0088cc]

出力例
```
-nan
2022
```

ただし、`lgamma` は飽くまでガンマ関数の「絶対値」の対数であることに注意する。
ガンマ関数の引数が負になる場合はガンマ関数が負になりうるので符号は別に求める必要がある。

##
```cpp example
Expand Down

0 comments on commit e1febaf

Please sign in to comment.