# 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

- 25
Churning round and round in the basement, the washing machine usually spends its' useful life as an unappreciated member of the appliance family...

- 86
Ever been to a NASCAR race? I thought not. Here are my top 10 reasons why NASCAR racing doesn't rock.

- 12
Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java.