MAINT: optimize.root_scalar: raise when NaN is encountered #17622
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Reference issue
Closes gh-3089
Closes gh-8394
Closes gh-14414
What does this implement/fix?
The bracketing scalar root-finders can return incorrect results when the function returns NaN. Instead, raise an error.
Additional information
The linked issues only report problems when the function is NaN at one of the initial bracketing interval endpoints, so the approach of the first commit was to only check for NaNs at the bracketing interval endpoints. However, I imagine there could also be problems if the solver does not encounter a NaN at the initial endpoints but later. One option is to also check whether the final function value is NaN, but this is not guaranteed to catch problems, and it could allow the algorithm to proceed long after the first NaN is encountered. I ended up changing the approach to check for NaN on every function evaluation using a wrapper. The performance hit seems small. In main:
with this PR:
This could probably be reduced by doing the NaN check in the compiled code itself as is discussed in #8394 (comment), but since gh-3089 was reported almost a decade ago, it seems there is some hesitation to modify all those compiled functions.