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

Visual Basic

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

More by this Author


Comments 2 comments

SimeyC profile image

SimeyC 7 years ago from NJ, USA

Nice method - long time since I did anything in VB!!!


nicomp profile image

nicomp 7 years ago from Ohio, USA Author

Thanks!

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working