KatInterview

Approximate a Square Root to the Nearest Tenth

Math & Bit ManipulationAuto-graded · 20 test cases
MediumAuto-gradedMath & Bit Manipulationbinary-searchnumerical-methodsfloating-point

Last 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

  • x may 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.4 or 3.0. A result that is a whole number is returned as that number with a zero tenth, so x = 9 gives 3.0.
  • If x is 0, return 0.0.
  • If x is negative, raise a ValueError.
  • 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 9 down to 2.9.

Constraints

  • 0 <= x <= 10^9
  • x is 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.