Skip to content

fix: improve accuracy in the tails for stats/base/dists/truncated-normal/pdf - #17150

Open
Udaygund wants to merge 2 commits into
stdlib-js:developfrom
Udaygund:fix/truncated-normal-pdf-tail
Open

Udaygund wants to merge 2 commits into
stdlib-js:developfrom
Udaygund:fix/truncated-normal-pdf-tail

Conversation

@Udaygund

@Udaygund Udaygund commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #17149.

Description

What is the purpose of this pull request?

This pull request:

  • fixes stats/base/dists/truncated-normal/pdf (lib/main.js, lib/factory.js, and src/main.c) returning Infinity, NaN, or inaccurate values when both endpoints lie in the upper tail (e.g., pdf( 11.0, 10.0, 12.0, 0.0, 1.0 ) returned Infinity instead of 2.7807e-4), and NaN in either tail when exp(-z^2/2) underflows.

  • when both endpoints lie on the same side of mu, at least two standard deviations away from it (a - mu >= 2*sigma or mu - b >= 2*sigma), lets c be the endpoint closest to mu and o the other one, and computes

    pdf = exp( (zc-z)*(zc+z)/2 ) / ( sigma * sqrt(2*pi) * 0.5 * ( erfcx(|zc|/sqrt(2)) - erfcx(|zo|/sqrt(2)) * exp( (zc-zo)*(zc+zo)/2 ) ) )
    

    which follows from Q(t) = 1 - Phi(t) = 0.5 * exp(-t^2/2) * erfcx(t/sqrt(2)) (and Phi(-t) = Q(t)) after dividing both the numerator and the normalizing constant by exp(-zc^2/2). Differences of squares such as zc^2 - z^2 are computed from the inputs, as ((c-x)/sigma) * ((c-mu)+(x-mu))/sigma, rather than from the standardized values, which keeps the error in the lower tail at the level of the previous implementation.

  • keeps the previous formula otherwise. Closer to mu, the previous formula is more accurate (see below for how the threshold was chosen).

Related Issues

Does this pull request have any related issues?

This pull request has the following related issues:

Questions

Any questions for reviewers of this pull request?

While writing the C implementation, I found that STDLIB_CONSTANT_FLOAT64_SQRT_HALF in constants/float64/sqrt-half/include/stdlib/constants/float64/sqrt_half.h is defined as 7.071067811865475244 (missing e-01), so it is ten times too large. I therefore used x / STDLIB_CONSTANT_FLOAT64_SQRT2 (and x / SQRT_TWO in JavaScript, to keep both implementations identical) instead of multiplying by SQRT_HALF. As far as I can tell, no C code uses this macro (the rayleigh packages use SQRT_HALF_PI, which is correct). Should I open a separate issue for it?

Other

Any other information relevant to this pull request? This may include screenshots, references, and/or implementation notes.

New tests (JS, native, and a new test.factory.js) use 9 cases in both tails, including infinite endpoints. Reference values were computed with Python's decimal module at 130 digits from phi(z) / ( sigma * ( Q(za) - Q(zb) ) ), with erfc evaluated from its power series and continued fraction (checked against math.erfc). The new implementation is within 3 ULP of all of them in both JS and C (tolerance 5 ULP); the previous one fails all 9 (from 17 ULP to Infinity/NaN). A second test uses 9 intervals close to mu (including intervals ending at mu and intervals just below and above the threshold), where all implementations are within 12 ULP (tolerance 15 ULP; the narrow interval [0.3, 0.4] is ill-conditioned).

On 300 random cases (endpoints up to 15 standard deviations from mu, including narrow intervals), relative to the same references:

max relative error errors > 1e-12 Infinity/NaN
previous 0.38 45 63
new (JS, factory, and C) 2.7e-14 0 0

(The column "errors > 1e-12" counts finite results only.)

To choose the threshold, I compared both formulas on 578 intervals with the nearest endpoint 0 to 3 standard deviations from mu and widths from 1e-8 to 10 standard deviations. The erfcx form is more accurate from about 1.8 standard deviations upward, but up to about 30 times less accurate closer to mu (e.g., [0, 1e-8], [0.3, 0.4]), so it is used only from 2 standard deviations. For very narrow intervals, both formulas lose digits to cancellation in the normalizing constant, roughly in proportion to 1/(b-a); this pull request does not change that. On the 300 random cases, the new implementation is worse than the previous one by at most 2.9e-15 relative error, and the JS and C implementations agree to within 2 ULP.

Ran locally: the JS and native tests (native addon built), all passing, plus the JS linter and cppcheck.

Checklist

Please ensure the following tasks are completed before submitting this pull request.

  • Read, understood, and followed the [contributing guidelines][contributing].

AI Assistance

When authoring the changes proposed in this PR, did you use any kind of AI assistance?

  • Yes
  • No

If you answered "yes" above, how did you use AI assistance?

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Disclosure

If you answered "yes" to using AI assistance, please provide a short disclosure indicating how you used AI assistance. This helps reviewers determine how much scrutiny to apply when reviewing your contribution. Example disclosures: "This PR was written primarily by Claude Code." or "I consulted ChatGPT to understand the codebase, but the proposed changes were fully authored manually by myself.".


@stdlib-js/reviewers

…rmal/pdf`

When both endpoints lie on the same side of `mu`, evaluates the
normalizing constant relative to the density at the endpoint closest to
`mu` using `erfcx`, avoiding the cancellation of `Phi(zb) - Phi(za)` and
the underflow of `exp(-z^2/2)`.

Resolves: stdlib-js#17149

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
type: pre_commit_static_analysis_report
description: Results of running static analysis checks when committing changes.
report:
  - task: lint_filenames
    status: passed
  - task: lint_editorconfig
    status: passed
  - task: lint_markdown_pkg_readmes
    status: na
  - task: lint_markdown_docs
    status: na
  - task: lint_markdown
    status: na
  - task: lint_package_json
    status: na
  - task: lint_repl_help
    status: na
  - task: lint_javascript_src
    status: passed
  - task: lint_javascript_cli
    status: na
  - task: lint_javascript_examples
    status: na
  - task: lint_javascript_tests
    status: passed
  - task: lint_javascript_benchmarks
    status: na
  - task: lint_python
    status: na
  - task: lint_r
    status: na
  - task: lint_c_src
    status: missing_dependencies
  - task: lint_c_examples
    status: na
  - task: lint_c_benchmarks
    status: na
  - task: lint_c_tests_fixtures
    status: na
  - task: lint_shell
    status: na
  - task: lint_typescript_declarations
    status: passed
  - task: lint_typescript_tests
    status: na
  - task: lint_license_headers
    status: passed
---
@Udaygund
Udaygund requested a review from a team December 4, 2026 14:00
@stdlib-bot stdlib-bot added Statistics Issue or pull request related to statistical functionality. Needs Review A pull request which needs code review. labels Dec 4, 2026
@stdlib-bot

stdlib-bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Coverage Report

Package Statements Branches Functions Lines
stats/base/dists/truncated-normal/pdf $\\color{green}393/393$
$\\color{green}+20.62\\%$
$\\color{green}42/42$
$\\color{green}+0.00\\%$
$\\color{green}4/4$
$\\color{green}+50.00\\%$
$\\color{green}393/393$
$\\color{green}+20.62\\%$

The above coverage report was generated for the changes in this PR.

…dard deviations from `mu`

For intervals closer to `mu`, the difference of the erfcx terms is
less accurate than `Phi(zb) - Phi(za)` (e.g., up to 30 times larger
errors for `[0, 1e-8]` and `[0.3, 0.4]`). The crossover is near
`1.8` standard deviations. Also adds tests for intervals near `mu`
and a test file for the `factory` method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
type: pre_commit_static_analysis_report
description: Results of running static analysis checks when committing changes.
report:
  - task: lint_filenames
    status: passed
  - task: lint_editorconfig
    status: passed
  - task: lint_markdown_pkg_readmes
    status: na
  - task: lint_markdown_docs
    status: na
  - task: lint_markdown
    status: na
  - task: lint_package_json
    status: na
  - task: lint_repl_help
    status: na
  - task: lint_javascript_src
    status: passed
  - task: lint_javascript_cli
    status: na
  - task: lint_javascript_examples
    status: na
  - task: lint_javascript_tests
    status: passed
  - task: lint_javascript_benchmarks
    status: na
  - task: lint_python
    status: na
  - task: lint_r
    status: na
  - task: lint_c_src
    status: missing_dependencies
  - task: lint_c_examples
    status: na
  - task: lint_c_benchmarks
    status: na
  - task: lint_c_tests_fixtures
    status: na
  - task: lint_shell
    status: na
  - task: lint_typescript_declarations
    status: passed
  - task: lint_typescript_tests
    status: na
  - task: lint_license_headers
    status: passed
---

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Needs Review A pull request which needs code review. Statistics Issue or pull request related to statistical functionality.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: stats/base/dists/truncated-normal/pdf returns Infinity, NaN, or inaccurate values when both endpoints lie in the upper tail

2 participants