Option Explicit
Option Private Module
Private error As Variant
Private iterations As Integer
Private title As String
Function getInitialApproximation(n As Variant) As Variant
Dim integerPart As Variant
Dim length As Integer
Dim guess As Variant
Dim ONE As Variant
ONE = CDec("1.00000000000000000000000000000000")
integerPart = Round(n, 0)
length = Len(integerPart)
If (length Mod 2 = 0) Then
length = length  1
End If
length = length / 2
guess = CDec(ONE * 10 ^ length)
getInitialApproximation = guess
End Function
Function getBigSquareRoot(n As Variant) As Variant
Dim initialGuess As Variant
Dim guess, lastGuess As Variant
Dim more As Boolean
Dim ZERO, ONE, TWO As Variant
ZERO = CDec("0.0000000000000000000000000000")
ONE = CDec(" 0.0000000000000000000000000001")
TWO = CDec(" 2.0000000000000000000000000000")
If (n <= ZERO) Then Exit Function
initialGuess = getInitialApproximation(n)
lastGuess = ZERO
guess = initialGuess
iterations = 0
more = True
While (more)
lastGuess = guess
guess = CDec(n / guess)
guess = CDec(guess + lastGuess)
guess = CDec(guess / TWO)
iterations = iterations + 1
If Abs(lastGuess  guess) <= ONE Then
more = False
End If
Wend
error = CDec(n  guess * guess)
If Abs(error) > Abs(getDoubleSquareRootError(n)) Then
guess = Sqr(n)
End If
getBigSquareRoot = CDec(guess)
End Function
Function getDoubleSquareRootError(n As Variant) As Double
Dim sqrt As Double
Dim error As Double
sqrt = Sqr(n)
error = (n  sqrt * sqrt)
getDoubleSquareRootError = error
End Function
Sub main()
Dim n, sqrt, nIterations As Variant
Dim testNums() As Variant
Dim response As Integer
title = "HighPrecision Square Root Calculator"
10:
n = InputBox(Prompt:="Input Value for Square Root Calculation", _
title:=title)
If n = "" Then
Exit Sub
Else
On Error GoTo CatchTypeError
n = CDec(n)
End If
If n <= 0 Then
InvalidNumberError
GoTo 10
Exit Sub
End If
On Error GoTo CatchSqrRootError
sqrt = getBigSquareRoot(n)
response = MsgBox(Prompt:="Paste Results in Active Cell?", _
title:=title, _
Buttons:=vbYesNo + vbInformation)
If response = VbMsgBoxResult.vbYes Then
Application.ActiveCell.Value = sqrt
End If
MsgBox Prompt:="Computing the square root of: " & n & vbCrLf _
& "Iterations: " & iterations & vbCrLf _
& "Sqrt: " & sqrt & vbCrLf _
& "Sqrt Squared: " & sqrt * sqrt & vbCrLf _
& "Error: " & error, _
title:=title, _
Buttons:=vbApplicationModal
Exit Sub
CatchTypeError:
InvalidNumberError
Err = False
Resume 10
Exit Sub
CatchSqrRootError:
MsgBox Prompt:="Calculation Error" & vbCrLf _
& "Value Probably Exceeds Limits", _
title:=title, _
Buttons:=vbExclamation
Err = False
Resume 10
Exit Sub
End Sub
Sub InvalidNumberError()
Dim msg As String
msg = "Invalid Number" & vbCrLf _
& "Please enter number >= 0 and" & vbCrLf _
& "<=79,228,162,514,264,337,593,543,950,335"
MsgBox Prompt:=msg, _
title:=title, _
Buttons:=vbExclamation
End Sub
Sub Button1_Click()
main
End Sub
