Skip to content

squareRoot(6) returns 3, squareRoot(12) returns 4; test expects squareRoot(3, 1) = 1.8 (correct: 1.7) #2231

Open

Description

@devladpopov

src/algorithms/math/square-root/squareRoot.js stops Newton's iteration when |number - root²| <= 10^-tolerance (line 31). That bounds the error of the square, not of the root. Newton's method approaches √n from above, so the loop stops on an overestimate, and rounding then goes the wrong way.

squareRoot(6);     // 3     expected 2   (√6 = 2.449)
squareRoot(12);    // 4     expected 3   (√12 = 3.464)
squareRoot(3, 1);  // 1.8   expected 1.7 (√3 = 1.732)

squareRoot.test.js:30 asserts expect(squareRoot(3, 1)).toBe(1.8), so the test enshrines the bug. For n = 0..3000 and tolerance 0..6 there are 68 wrong results.

Fix: iterate until the root stops decreasing (while (next < root)), then round. Checked on 259,695 inputs against correctly rounded Math.sqrt; the only mismatches are 53 last-digit float effects at tolerance >= 10. This also removes the hang reported in #2187 (squareRoot(65549, 11)). The #2187 change alone still returns 3 and 1.8.


Found during an independent property-based audit of this repo (full report and reproducible harness: https://github.com/devladpopov/algorithm-autopsy/tree/main/autopsy-02).

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions