- Computers & Software»
- Computer Science & Programming
Calculating a Square Root in Microsoft .Net with Visual Basic
This tutorial illustrates an adaptation of the Newton method for calculating square roots. Written in Visual Basic and implemented in Visual Basic .Net, this code simply iterates until a reasonably close approximation is calculated.
The square root approximation is governed by the value of the variable epsilon, declared and initialized in line 5.
Function SquareRoot(ByVal x As Double) As Double Dim g As Double Dim root As Double Dim tmp As Double Const epsilon = 0.00001 'Add some error handling Try 'Start with a guess in the variable g g = 2 Do While True ' Infinite Loop. The condition can never become false 'Calculate x / g tmp = x / g 'Calculate (x/g) squared tmp = tmp * tmp 'Check to see how close we are to the answer If System.Math.Abs(tmp - x) <= epsilon Then Return x / g ' Send the answer back to the calling procedure End If 'Recalculate the guess g = ((x / g) + g) / 2 'Start the loop over Loop Catch ' Errors end up here MsgBox("Unable to calculate square root: " & Err.Description, MsgBoxStyle.Critical, "oops") End Try End Function
Of course, Microsoft has included a square root function in the .Net framework. Our code can be replaced with:
Function SquareRoot(ByVal x As Double) As Double Return Math.Sqrt(x) End Function