Results 1 to 16 of 16

Thread: Square Root

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    83

    Square Root

    This is my first code ive submitted so it wont be that good.

    VB Code:
    1. Public num As Integer
    2.  
    3. Public Function SquareRoot(TextBox As String)
    4. On Error Resume Next
    5. num = 1
    6. Do
    7. num = num + 1
    8. If num * num = TextBox Then Exit Do
    9. Loop
    10. MsgBox num
    11. End Function

    To use, put
    VB Code:
    1. SquareRoot(25) 'change number
    In your form.
    Last edited by SlicedCheese; Jan 25th, 2006 at 11:17 AM.

  2. #2
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Square Root

    Fine job, but I would point out one thing.

    The Error Trap code will always execute unless you add an Exit Sub right before the Error Trap label.

  3. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Square Root

    Quote Originally Posted by Hack
    Fine job, but I would point out one thing.

    The Error Trap code will always execute unless you add an Exit Sub right before the Error Trap label.
    Actually it will not since he use a (yuck) GoTo statement that returns it back to the top where he checks if num * num <> the number to take the square root of. The error trap is in the Else clause and unless an error actually occurs it will never reach that part.

    BTW, why not use the built in Sqr() function?

  4. #4
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Square Root

    Quote Originally Posted by Joacim Andersson
    Actually it will not since he use a (yuck) GoTo statement that returns it back to the top where he checks if num * num <> the number to take the square root of. The error trap is in the Else clause and unless an error actually occurs it will never reach that part.
    That was my kind of round about way of inferring the Goto be replaced with an Exit Sub.

  5. #5
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Square Root

    It wouldn't work with an exit sub instead of the goto at that position. However a regular Do While loop would be so much cleaner then using an If together with a goto.

    Also there are other logical errors with the code since it can only determent the square root of a number in which the square root itself is an integer... like 2, 4, 9, 16, 25, 36 and so on. Trying it with a number like 10 or 7 or something will eventually raise an overflow error.

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    83

    Re: Square Root

    Ah, i didnt think about Do loop, ive updated it.

  7. #7
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Square Root

    But what if I wanted to know the square root of 26?

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    83

    Re: Square Root

    I dunno, im trying to fix it somehow

  9. #9
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Square Root

    But as I already mentioned, VB already has a built in function for this. It's called Sqr().
    VB Code:
    1. MsgBox Sqr(25)

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    83

    Re: Square Root

    Yes, but im trying to build my own

  11. #11
    Admodistrator |2eM!x's Avatar
    Join Date
    Jan 2005
    Posts
    3,900

    Re: Square Root

    Quote Originally Posted by SlicedCheese
    Yes, but im trying to build my own
    Then learn a square root algo:
    http://www.google.com/search?hs=3qu&...ot&btnG=Search

  12. #12

  13. #13
    New Member
    Join Date
    Jul 2008
    Posts
    4

    Re: Square Root

    Quote Originally Posted by SlicedCheese
    This is my first code ive submitted so it wont be that good.

    VB Code:
    1. Public num As Integer
    2.  
    3. Public Function SquareRoot(TextBox As String)
    4. On Error Resume Next
    5. num = 1
    6. Do
    7. num = num + 1
    8. If num * num = TextBox Then Exit Do
    9. Loop
    10. MsgBox num
    11. End Function

    Since this post is two years old, I'll assume that SlicedCheese has either completed his homework or failed. Some suggestions:
    1. Your Function SquareRoot() will default to the Variant data type, since you failed to declare one. While this will work, it should be declared as a Double, so it can more efficiently return rational results, e.g., the square root of 27 = 5.19615242270663.
    2. If you plan to use the function throughout your application, put it in a public module or make a math class with various math functions in it.
    3. Making the variable num global is bad practice. Best practice is to declare (i.e., Dim) num local to (i.e., inside of) your function so that it lives and dies there each time the function is called.
    4. The variable num should also be declared a Double, instead of an Integer, as the latter will return "0" for rational results.
    5. Change the SquareRoot() parameter TextBox As String to a Variant so it can accept various input types.
    6. The statement num * num will raise your input to the power of 2 (e.g., x^2), not calculate the square root. To calculate a square root in VB without using VB's Sqr() function, raise the number to the equivalent fractional power, e.g., x^(1/2). This is high school math.
    7. If you want to loop through a set of numbers to calculate their square roots, do so in a separate procedure, and call SquareRoot() from there.
    8. Finally, you should conditionally trap your errors at the bottom of the function.


    This example is clean, unambiguous, self documenting, and maintainable code. I've replaced the variable num with dBase. This example could be improved by fine tuning the conditional error check. Since this is a wasteful redundancy of VB's Sqr() function, a more useful exercise, left to the reader, would be to code a function that can calculate any root , e.g., cube root, 4th root, etc.:

    VB Code:
    1. Private Sub cmdCalcSqrt_Click()
    2.     Dim dOutput As Double
    3.    
    4.     lblResult = ""
    5.     dOutput = Sqrt(txtInput)
    6.    
    7.     If dOutput > 0 Then
    8.         lblResult.Caption = "{" & dOutput & ", -" & dOutput & "}"
    9.     Else
    10.         Dim sErrPrompt As String   'Dim sErrPrompt  <-- Corrected at Errata 2
    11.         sErrPrompt = "Error: Could not calculate root. " & vbCrLf & _
    12.                      "Check your input."
    13.         ShowErrorMsg (sErrPrompt)
    14.     End If
    15. End Sub
    16.  
    17. Private Function Sqrt(vRadicand As Variant) As Double
    18.     On Error GoTo ErrHandler:
    19.     Dim dBase As Double
    20.    
    21.     dBase = CDbl(vRadicand)
    22.     Sqrt = dBase ^ (1 / 2)
    23. Exit Function   '<-- Corrected at Errata 3
    24. ErrHandler:
    25.     If Err.Number > 0 Then
    26.         Dim sErrPrompt As String   'Dim sErr As String <-- Corrected at Errata 1
    27.         sErrPrompt = "Error No. " & Err.Number & " @ Function SquareRoot." & vbCrLf & _
    28.                      "Description: " & Err.Description
    29.         ShowErrorMsg (sErrPrompt)
    30.     End If
    31. End Function
    32.  
    33. Private Sub ShowErrorMsg(sErrPrompt As String)
    34.     MsgBox sErrPrompt, vbExclamation, "Error!"
    35. End Sub
    Last edited by bearded_oneder; Jul 8th, 2008 at 04:03 PM.

  14. #14
    New Member
    Join Date
    Jul 2008
    Posts
    4

    Re: Square Root

    Errata:
    OOPS! Turning Option Explicit on revealed a Variable not defined error on line 27, caused by an incomplete variable name on line 26. Lines 24 - 30 debugged,

    VB Code:
    1. ErrHandler:
    2.     If Err.Number > 0 Then
    3.         Dim sErrPrompt As String
    4.         sErrPrompt = "Error No. " & Err.Number & " @ Function SquareRoot." & vbCrLf & _
    5.                      "Description: " & Err.Description 'Line 27 wrapped
    6.         ShowErrorMsg (sErrPrompt)
    7.     End If

  15. #15
    New Member
    Join Date
    Jul 2008
    Posts
    4

    Re: Square Root

    Errata 2: Declared data type for sErrPrompt on line 10,

    VB Code:
    1. Dim sErrPrompt As String

  16. #16
    New Member
    Join Date
    Jul 2008
    Posts
    4

    Re: Square Root

    Errata 3: To improve efficiency, inserted Exit Function at line 23. This avoids processing the statements after the ErrHandler: label each time the function is called, even when no error has occurred.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width