Repository navigation
Fix squareRoot returning overestimates (squareRoot(6) = 3) - #2250
Open
devladpopov wants to merge 1 commit into
Open
devladpopov wants to merge 1 commit into
devladpopov wants to merge 1 commit into
Conversation
The loop stopped when |number - root^2| <= 10^-tolerance. That bounds the error of the square, not of the root, so it could stop on an overestimate: squareRoot(6) returned 3 and squareRoot(12) returned 4. Iterate Newton's method until the approximation stops decreasing and round only at the end. Fix the test that expected squareRoot(3, 1) to be 1.8 (sqrt(3) = 1.732...) and add regression tests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fixes #2231
The loop stopped once
|number - root^2| <= 10^-tolerance. That bounds the error of the square, not of the root, so Newton's method could stop on an overestimate and the final rounding made it visible:squareRoot(6)squareRoot(12)squareRoot(3, 1)Change: starting from 1, after the first Newton step the approximation is never below the root (AM-GM) and every next step moves it down. So the loop now runs while the approximation keeps decreasing, which gives the root at full float precision, and rounding to
tolerancedigits happens only at the end. No new parameters, same signature.Tests:
squareRoot(3, 1)from 1.8 to 1.7 (sqrt(3) = 1.732...)squareRoot(6) = 2,squareRoot(12) = 3,squareRoot(35) = 6,squareRoot(99) = 10, plus tolerance casesMath.sqrtnpm run lintandnpm testpass (178 suites, 589 tests).