ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Calculating a Square Root in Microsoft .Net with Visual Basic

Updated on August 28, 2009

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

Comments

    0 of 8192 characters used
    Post Comment

    • SimeyC profile image

      Simon Cook 7 years ago from NJ, USA

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

    • nicomp profile image
      Author

      nicomp really 7 years ago from Ohio, USA

      Thanks!

    Click to Rate This Article