I can not for the life of me figure out how to solve for a cubic equation using visual basic. I have tried multiple codes found on the internet, but they do not work or there is code I do not understand (such as root.root).

Here is the equation I am trying to solve. Van der Waals equation

I am in a bind, this project is due Friday. Fortunately I have everything else done just need this peice.

Your help will be much appreciated.

This is how to find the real roots using Newton’s method:

Function realCubeRoot(a, b, c, d, n)
    '
    ' computes the nth real root of the cubic equation
    '
    ' a x^3 + b x^2 + c x + d = 0
    '
    ' =================================================
    xold = 1
    iter = 0
    Do
        iter = iter + 1
        f = a * xold ^ 3 + b * xold ^ 2 + c * xold + d
        df = 3 * a * xold ^ 2 + 2 * b * xold + c
        xnew = xold - f / df
        Err = xnew - xold
        xold = xnew
    Loop While (iter < 1000) And (Abs(Err) > 0.000001)
    If n = 1 Then
        realCubeRoot = xnew
    Else
        aa = b / a
        bb = c / a
        Real = -(aa + xnew) / 2
        Disc = (-3 * xnew ^ 2 - 2 * aa * xnew + aa ^ 2 - 4 * bb)
        If Disc < -0.0000001 Then
            realCubeRoot = "NA"
        Else
            Disc = Abs(Disc)
            If n = 2 Then
                realCubeRoot = Real + Disc ^ (1 / 2) / 2
            Else
                realCubeRoot = Real - Disc ^ (1 / 2) / 2
            End If
        End If
    End If
End Function

Private Sub Command1_Click()
    MsgBox realCubeRoot(5, 2, 2, 4, 1)
End Sub
Comments
Helping as always.

Do I dim all variables as double? Also I have the cubic root in the form of "x^3 + ax^2 + bx + c = 0", is there anything I need to do to account for this?

Oh thank you for the quick response. I am creating, in my opinion, an awesome program for my skill level. I will post it to get some criticism from the community.

THANK YOU THANK YOU THANK YOU... I can't say it enough.

@ JX_Man

I don't know what to say.... IT WORKS!!!! same answer wolfram alpha gives. I just got done jumping up and down yelling SUCCESS. I would write more but I have to finish this program then study for a Transport Phenomenon final. WOOT

What are these values for? ------> MsgBox realCubeRoot(5, 2, 2, 4, 1)

If they are my values for my equation, what should I set "n" to

9f2f0d837a9e72a448d0aa95988a36e3

e.g :

Private Sub Command1_Click()
    ' x^3 - 7x - 6 = 0 (ans : -2, -1 or 3)
    MsgBox realCubeRoot(1, 0, -7, -6, 0)
    MsgBox realCubeRoot(1, 0, -7, -6, 1)
    MsgBox realCubeRoot(1, 0, -7, -6, 2)

    ' x^3 - 5x^2 - 2x + 24 = 0 (ans : -2, 3 or 4)
    MsgBox realCubeRoot(1, -5, -2, 24, 0)
    MsgBox realCubeRoot(1, -5, -2, 24, 1)
    MsgBox realCubeRoot(1, -5, -2, 24, 2)

End Sub
This question has already been answered. Start a new discussion instead.