SquareRoot { public float calculateSquareRootIterative(int number) { float candidate = 1f; while (candidate * candidate <= number) { candidate++; } candidate--; if (isGoodResultForSqrt(number, candidate * candidate)) { return candidate; } float top = candidate + 1; float bottom = candidate; float newCandidate = (top + bottom) / 2; float result = newCandidate * newCandidate; while (!isGoodResultForSqrt(number, result)) { if (result > number) { top -= 0.1f; } else { bottom -= 0.1f; } newCandidate = (top + bottom) / 2; result = newCandidate * newCandidate; } return Math.abs(newCandidate); }  float calculateSquareRootIterative(int number); float calculateSquareRootRecursive(int number);  }
@Test public void squareRootOfFourEqualsToTwo() { float result = squareRoot.calculateSquareRootIterative(4); assertEquals(2, result, DELTA); }
@Test public void squareRootOfNineEqualsToThreeIterative() { float result = squareRoot.calculateSquareRootIterative(9); assertEquals(3, result, DELTA); }
@Test public void shouldCalculateNonPerfectSquaresIterative() { float result = squareRoot.calculateSquareRootIterative(7); assertEquals(2.64575f, result, DELTA); }
@Test public void shouldCalculateSquaresOfTwoDigitsIterative() { float result = squareRoot.calculateSquareRootIterative(12); assertEquals(3.46410f, result, DELTA); }