Approximate a Square Root to the Nearest Tenth
Math & Bit ManipulationAuto-graded · 20 test casesLast updated
Compute the square root of a non-negative number without a built-in root function and return it rounded to one decimal place, using bisection or Newton's method.
Square Root to One Decimal Place
Write a function that takes a non-negative number x and returns the square root of x, rounded to the nearest tenth (one digit after the decimal point). Round half up.
You must not use any built-in square root routine. This rules out math.sqrt, x ** 0.5, pow(x, 0.5), math.isqrt, numpy.sqrt and similar. You must compute the root yourself with an iterative or search-based method.
Details
xmay be an integer or a non-integer real number, and it may be smaller than 1.- The returned value is a float, such as
1.4or3.0. A result that is a whole number is returned as that number with a zero tenth, sox = 9gives3.0. - If
xis0, return0.0. - If
xis negative, raise aValueError. - Assume the true root never lies exactly halfway between two tenths, so tie-breaking between neighbouring tenths does not matter.
- Your computation must be accurate enough that the rounded result is correct. Make sure approximating from one side does not push a perfect square such as
9down to2.9.
Constraints
0 <= x <= 10^9xis a finite real number (int or float).- The result must be within rounding of the true root: the returned value is the tenth nearest to the real square root.
- No built-in square root functions.
Examples
Example 1
Input: sqrt_nearest_tenth(2)
Output: 1.4
Example 2
Input: sqrt_nearest_tenth(9)
Output: 3
Example 3
Input: sqrt_nearest_tenth(0)
Output: 0
Hints
Hint 1
The function m*m is increasing for m >= 0, so you can search for the m where m*m reaches x. Think about what interval is guaranteed to contain the root, and remember that for 0 < x < 1 the root is larger than x.
Hint 2
Search with much finer precision than a tenth, then round only once at the end. Stopping at a coarse interval can give the wrong tenth.
Hint 3
If your estimate approaches the root from below, truncating can turn 3.0 into 2.9. Round with something like floor(value * 10 + 0.5) / 10 instead. Newton's iteration m = (m + x/m) / 2 is a faster alternative to bisection.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function m -> m*m is increasing for m >= 0, so the square root of x is the unique point where it reaches x. That makes bisection a natural fit.
- Handle the edge cases first. A negative
xraisesValueError, andx = 0returns0.0. - Choose the search interval
[0, max(1, x)]. Forx >= 1the root is at mostx. For0 < x < 1the root is larger thanxbut still at most1. Usingmax(1, x)as the upper bound covers both cases. - Repeat 100 times: take the midpoint
mid. Ifmid*mid < x, the root is to the right, so setlo = mid. Otherwise sethi = mid. Each step halves the interval. - After the loop,
lois within floating-point resolution of the true root. Round once withint(lo * 10 + 0.5) / 10. Becauselo >= 0,intacts as floor, so this is round-half-up.
Why it is correct
The loop keeps the invariant lo*lo < x <= hi*hi, so the root always stays inside [lo, hi]. After 100 halvings the width is about hi0 / 2^100, which for x <= 1e9 is far below double precision. Searching to that precision and rounding only at the end ensures the result is the nearest tenth.
Since lo approaches the root from below, a perfect square like 9 leaves lo just under 3. Rounding (adding 0.5 before flooring) correctly gives 3.0, whereas truncating would wrongly give 2.9.
Complexity
- Time: O(1) for the fixed 100 iterations. In general bisection needs O(log(R / eps)) steps to reach tolerance
epsover a rangeR. - Space: O(1).
Alternatives
- Newton's method,
m = (m + x / m) / 2, converges quadratically and reaches double precision in a handful of steps from a reasonable starting guess. - An integer approach finds the largest integer
kwithk*k <= 100*xby binary search and avoids floating-point drift entirely.
Reference solution
def sqrt_nearest_tenth(x: float) -> float:
if x < 0:
raise ValueError("x must be non-negative")
if x == 0:
return 0.0
lo = 0.0
hi = max(1.0, x)
# Bisection: shrink the interval far below the precision we need.
for _ in range(100):
mid = (lo + hi) / 2.0
if mid * mid < x:
lo = mid
else:
hi = mid
# Round half up to one decimal place (lo >= 0, so int() acts as floor).
return float(int(lo * 10.0 + 0.5)) / 10.0