josdejong / josdejong/mathjs

lgammaNumber incorrectly returns NaN for all n < 0

Open
#3,604 6 comments 0 reactions 0 assignees View on GitHub
bug category:numerical help wanted
Dominant language
JavaScript
Stars
15.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

### Describe the bug
`lgammaNumber` incorrectly returns `NaN` for all `n < 0`.

### To Reproduce
1. Call `mathjs.log(mathjs.gamma(-1.5))` and get `0.8600470153764809`.
2. Call `mathjs.lgamma(-1.5)` and get `NaN`.
3. See that the returned values are not equal.

### Problematic code
https://github.com/josdejong/mathjs/blob/4bbe862bb553bd765685b46d977e8ee226e4abf0/src/plain/number/probability.js#L91-L92

### Suggested solution
Change the code
```js
return NaN
```
to
```js
Math.log(Math.PI / Math.sin(Math.PI * n)) - lgammaNumber(1 - n)
```
It correctly returns `NaN` for $n \in (-2k-1, -2k)$ and positive values for $n \in (-2k, -2k+1)$ for $k \in ℕ$.

You can check it for `-1.5` too: `Math.log(Math.PI / Math.sin(Math.PI * -1.5)) - mathjs.lgamma(1 - -1.5)` returns `0.8600470153764859`, which is close to `0.8600470153764809`.

You can also just remove this if statement, because the one below already handles the `n < 0` case properly:
https://github.com/josdejong/mathjs/blob/4bbe862bb553bd765685b46d977e8ee226e4abf0/src/plain/number/probability.js#L96-L100

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.