Results 1 to 16 of 16

Thread: Cube Root Error

  1. #1

    Thread Starter
    Fanatic Member Vectris's Avatar
    Join Date
    Dec 2008
    Location
    USA
    Posts
    941

    Cube Root Error

    Much to my disappointment I recently discovered that VB can not calculate the cube root (or any odd root) of a negative number even though it is a real answer.

    For instance if you try
    Code:
    MsgBox((-1)^(1/3))
    You should get -1 because -1*-1*-1 = -1. But no, VB will return NaN, not a number.

    Anyways, my problem is that I'm making a graph program and the user needs to be allowed to enter any formula they want and have it evaluated so the program can graph it. But if the user enters anything with x^(1/3) or like it, it will fail.

    So I was wondering if anyone knows of a way around this problem, such as an extension or patch or something that will fix the issue in Visual Basic. I haven't tried VB 2010 but does anyone know if they have they fixed it yet in that version?

    Also I can't just use Math.Abs because like I mentioned, the user could enter anything, so if they put something like this:

    (x - 250)^(1/3) + (x)^(1/x)

    It would be way to complex to evaluate everything in the parenthesis, check for the negatives that are being squared/rooted, take the absolute value, then finish the square, and then restore the sign.

    If there was an easier way to evaluate expressions in VB then maybe I could do something with parsing but as of now my method is by compiling the formula (string) the user entires as VB code and letting it solve itself by replacing x with the number I need for the coordinate.
    Last edited by Vectris; Feb 27th, 2010 at 11:37 PM.
    If your problem is solved, click the Thread Tools button at the top and mark your topic as Resolved!

    If someone helped you out, click the button on their post and leave them a comment to let them know they did a good job

    __________________
    My Vb.Net CodeBank Submissions:
    Microsoft Calculator Clone
    Custom TextBox Restrictions
    Get the Text inbetween HTML Tags (or two words)

  2. #2
    Lively Member
    Join Date
    Feb 2010
    Posts
    120

    Re: Cube Root Error

    well you can take out square root by this
    Code:
       MsgBox(Math.Sqrt(Textbox1.Text))

  3. #3

    Re: Cube Root Error

    @Watson: That isn't helping out Vectris

    @Vectris: This code is an example I found on the internet for finding a number to the nth root:

    vb.net Code:
    1. Dim firstnum As Double = Convert.ToDouble(textBox1.Text)
    2. Dim power As Double = 1D / 3D
    3. Dim secondnum As Double = Math.Pow(firstnum, power)
    4. label1.Text = secondnum.ToString()
    It was converted from C#, so I'm going to test it out real fast..

    After stepping through it, it returned -1.#IND. The .ToString() of that is NaN.

    EDIT: Did a little digging around and found this
    Last edited by formlesstree4; Feb 28th, 2010 at 12:52 AM.

  4. #4
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    The cube root of -1 is actually three numbers:


    This is the same as a square root. The square root of 4 is either 2 or -2, but the principle square root (the one people usually mean) is 2.

    Which answer is 'defined' as the principle cube root depends on your definition. If you define the cube root of x to be a number y such that y^3 = x, then the cube root of a negative number is a negative (real) number.

    If, however, you use polar coordinates to represent x, you can define the cube root as


    Then, the cube root of -8 (for example) is

    And not -2.

    Apparently something goes wrong in calculating the root and VB cannot see that there is also a real root (alongside the two complex roots that would give NaN). My guess is that the underlying functions that calculate roots (either the ^ operator or Math.Pow) simply return NaN when the base is negative.

    A workaround: just take the cube root of the positive number and multiply the result by -1.

  5. #5
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    Quote Originally Posted by formlesstree4 View Post
    .. code ..
    Just a little nitpicking, but the D suffix means Decimal, and not Double. For a Double, you use R (or simply 1.0):
    Code:
    Dim power As Double = 1R / 3R
    I think VB autocompletes this to
    Code:
    Dim power As Double = 1.0R / 3.0R
    (At least VS2010 does).

    But since 1.0 is Double by default you can also just use
    Code:
    Dim power as Double = 1.0 / 3.0
    Or even
    Code:
    Dim power As Double = 1 / 3
    Because the / operator returns a Double.

  6. #6
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Cube Root Error

    It seems like VB.NET can't calculate any roots of negative numbers.
    If you do
    Code:
    Msgbox( -4 ^ (1/2) )
    you still get a NaN, against your expectation of 2 or -2

    So they created a function Math.Sqrt(X) to deal with it.
    On similar grounds we create our own function to deal with cube roots.
    vb.net Code:
    1. Function CubeRoot(ByVal number As Double) As Double
    2.     If number >= 0 Then
    3.         Return number ^ (1 / 3)
    4.     Else
    5.         Return -1 * (-1 * number) ^ (1 / 3)
    6.     End If
    7. End Function

    This is based on the theorem:
    Code:
    cuberoot of (-x) = - (cuberoot of x)
    (couldn't figure out a way to put cuberoot sign here How do we do that?)
    Last edited by Pradeep1210; Feb 28th, 2010 at 07:18 AM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog • 101 LINQ Samples • JSON Validator • XML Schema Validator • "How Do I" videos on MSDN • VB.NET and C# Comparison • Good Coding Practices • VBForums Reputation Saver • String Enum • Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  7. #7
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    Quote Originally Posted by Pradeep1210 View Post
    It seems like VB.NET can't calculate any roots of negative numbers.
    If you do
    Code:
    Msgbox( -4 ^ (1/2) )
    you still get a NaN, against your expectation of 2 or -2
    I wouldn't expect it to return 2, because the square root of -4 is not 2, nor -2. 2*2 = 4 and -2*-2 = 4, but not -4.
    The square root of -4 is either 2i or -2i. And since VB knows no complex numbers, it is NaN.

  8. #8
    Frenzied Member
    Join Date
    Jul 2009
    Posts
    1,103

    Re: Cube Root Error

    Quote Originally Posted by NickThissen View Post
    I wouldn't expect it to return 2, because the square root of -4 is not 2, nor -2. 2*2 = 4 and -2*-2 = 4, but not -4.
    The square root of -4 is either 2i or -2i. And since VB knows no complex numbers, it is NaN.

    If you find my reply helpful , then rate it

  9. #9
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Cube Root Error

    ooohhhh... Forgot that. I'm an old man now.

    Thanks for correcting me.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog • 101 LINQ Samples • JSON Validator • XML Schema Validator • "How Do I" videos on MSDN • VB.NET and C# Comparison • Good Coding Practices • VBForums Reputation Saver • String Enum • Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  10. #10

    Thread Starter
    Fanatic Member Vectris's Avatar
    Join Date
    Dec 2008
    Location
    USA
    Posts
    941

    Re: Cube Root Error

    Thanks for the info but due to the nature of the project I can't just call a function that will take the cube root and then make it negative.

    A completely random formula is inputted, compiled as code, and then evaluated by visual basic. This makes it extremely hard to simply call a function for the root without writing a large parse code to find any root functions, re-compile and evaluate what's inside, check if it's negative, reverse it, and then square it. Not to mention if someone raised something to the 1/x power I'd have to evaluate that first to which would be a whole involve doing that all over again.
    If your problem is solved, click the Thread Tools button at the top and mark your topic as Resolved!

    If someone helped you out, click the button on their post and leave them a comment to let them know they did a good job

    __________________
    My Vb.Net CodeBank Submissions:
    Microsoft Calculator Clone
    Custom TextBox Restrictions
    Get the Text inbetween HTML Tags (or two words)

  11. #11
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    Well the simple answer is: if you let .NET read the input and compile it on the fly, then you are stuck with what .NET provides, so there is no solution to your problem.

    If you were to write a parser that parsed the input, your problem would be solved. Of course that takes some effort, but it's one or the other. And in my opinion, if this application is a serious job (and not just a test or something) then you should write your own parser anyway. I wouldn't rely on .NET to compile it for me, exactly due to things like this. You don't have the control you may want to have at a later stage.

  12. #12

    Thread Starter
    Fanatic Member Vectris's Avatar
    Join Date
    Dec 2008
    Location
    USA
    Posts
    941

    Re: Cube Root Error

    Thanks nick. Luckily this isn't for a job, yet (I'm going into computer science, specifically I want to deal with programming, but probably in a different language). Nor a test but simply a fun (haha, the things we call "fun") project I was doing on my own.

    As for the parser that was my first option however due to the difficulty I was hoping to find a work around, such as compiling the code. Either way it appears you are right and other than writing my own parser there is not much room to fix the cube root problem. Unfortunately parsing all the common math syntax and calculating things like what's in between parameters first etc. seems very difficult to me. I may give it a try but will probably post a separate topic about any suggestions for what approach to take. As of now I don't know regular expressions but I'm guessing they would be very handy in this case, you have any advice on whether I should learn that or if it would be about the same to just stick to indexof and the other basic string functions?
    If your problem is solved, click the Thread Tools button at the top and mark your topic as Resolved!

    If someone helped you out, click the button on their post and leave them a comment to let them know they did a good job

    __________________
    My Vb.Net CodeBank Submissions:
    Microsoft Calculator Clone
    Custom TextBox Restrictions
    Get the Text inbetween HTML Tags (or two words)

  13. #13
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    Quote Originally Posted by Vectris View Post
    Thanks nick. Luckily this isn't for a job, yet (I'm going into computer science, specifically I want to deal with programming, but probably in a different language). Nor a test but simply a fun (haha, the things we call "fun") project I was doing on my own.

    As for the parser that was my first option however due to the difficulty I was hoping to find a work around, such as compiling the code. Either way it appears you are right and other than writing my own parser there is not much room to fix the cube root problem. Unfortunately parsing all the common math syntax and calculating things like what's in between parameters first etc. seems very difficult to me. I may give it a try but will probably post a separate topic about any suggestions for what approach to take. As of now I don't know regular expressions but I'm guessing they would be very handy in this case, you have any advice on whether I should learn that or if it would be about the same to just stick to indexof and the other basic string functions?
    Parsing an equation is not rocket science, but it's not trivial either. I have tried a few times to write a simple parser but I just lost interest pretty quickly.

    The most promising algorithm is the shunting yard algorithm which simply reads the equation character by character and does something based on the character. The only difficulty I had trying to implement that (and I must say I've never taken the trouble to find a solution to the problem, as I said I lost interest) is that you need to know the precedence of operators (like multiplication has greater precedence than addition). I wanted to keep it general, with every operator having its own class that derives from some base class, so you could, in principle, add new operators on the fly. But I never figured out a nice way to incorporate this precedence without writing a large If / Select Case statement which simply compares the operator against all others...

    If I find some time I might give it another shot, hopefully this time I won't lose interest so quickly

  14. #14

    Thread Starter
    Fanatic Member Vectris's Avatar
    Join Date
    Dec 2008
    Location
    USA
    Posts
    941

    Re: Cube Root Error

    Haha I know how dropping a project goes. The thought of starting a fresh programming idea sometimes seems so much better than continuing an old one.

    As for how to structure the parse function my plan so far is to find the greatest operand in the order of operations, find both numbers connected to it, and solve that putting the resulting number back in place of the two intial ones. Basically solving the equation until there are no operators left. Of course to incorporate things like paranthesis I will have to adapt it to do all the insides first and then branch out but other than that I don't see too many holes, yet.

    The shunting yard algorithm is interesting however after a 5 minute read I couldn't figure out how to inteterpret the output and I didn't see how it accounted for the paranthesis. I'll use my method (basically one you tried) first and then go with it from there.

    Thanks for taking the time to fully read my first post and for the advice on the parser. Of course before all this I tried the codebank and google to find an existing parser but came up empty. However right before making this post this I tried again and found a pretty good one.

    http://www.codeproject.com/KB/vb/mat...evaluator.aspx

    It still has some problems though. Of course the cube root thing but also -3^(1/3) is NaN when it should evaluate the 3^(1/3) first. Another minor thing but it doesn't support multiplaction without the sign, such as 2(3). But that could be pretty easily fixed.

    It's always a little less interesting once you've found a working project but I think I'm going to at least give my own a try as it would definitely be good experience. Good luck to you if you decide to try it again sometime. You say you lost interest pretty quickly but out of curiosity, how far did you get?
    If your problem is solved, click the Thread Tools button at the top and mark your topic as Resolved!

    If someone helped you out, click the button on their post and leave them a comment to let them know they did a good job

    __________________
    My Vb.Net CodeBank Submissions:
    Microsoft Calculator Clone
    Custom TextBox Restrictions
    Get the Text inbetween HTML Tags (or two words)

  15. #15
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Cube Root Error

    The shunting yard algorithm produces the output in Reverse Polish Notation form. This form does not require the use of parenthesis and can be parsed very easily using a single stack. Just read the RPN form left to read. When a number is found, push it on the stack. When an operator is found, pop the two last numbers from the stack (or however many operands the operator requires), apply the operator to them, and push the result back on the stack. That's it really. However, I'm not really sure how to apply that to functions such as sin, cos, etc. I'm sure it's possible though.

    I only got the very basics: being able to convert a simple expression (using only binary operators such as +, *, -, ^, etc) to an RPN expression and finally calculating the value from that. It did not support anything like functions like sin, or functions with multiple values, etc, basically because it reads the expression left to read, one character at a time. For sin(x) it would suddenly read an 's' and that is neither an operator nor a value, so it would have to do something special there, but I never finished that.

  16. #16

    Thread Starter
    Fanatic Member Vectris's Avatar
    Join Date
    Dec 2008
    Location
    USA
    Posts
    941

    Re: Cube Root Error

    Ah I understand it now. I was confused about pushing things back on the stack. As for those functions I can see how that would be hard to compute them when it's not something simple involving two numbers.

    Not sure how much slower it would be but you could use your project, given the functions it has so far, to solve an entire expression recursively. Basically start by solving sin, cos, tan etc. functions first using your current evaluator to solve what's in the paranthesis. Then after you've given a value to all the sins, cos's, tans, etc. run it one more time to solve what's left. Biggest problem I see is time as it would have to create and solve a separate stack for all the stuff inside sin, cos, tan functions.
    If your problem is solved, click the Thread Tools button at the top and mark your topic as Resolved!

    If someone helped you out, click the button on their post and leave them a comment to let them know they did a good job

    __________________
    My Vb.Net CodeBank Submissions:
    Microsoft Calculator Clone
    Custom TextBox Restrictions
    Get the Text inbetween HTML Tags (or two words)

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