What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleGraph a user-entered function by parsing the function
DescriptionThis example shows how to graph a user-entered function by parsing the function in Visual Basic 6. The program steps through different X values, parsing and evaluating the function for each.
Keywordsgraph, equation, scale, user-entered function, parse
CategoriesStrings, Algorithms, Graphics
When the user clicks the Graph button, the program reads the entered equation, and X and Y bounds. It uses the picGraph control's Scale method to map these bounds onto the control's surface.

The program then clears the control and draws axes and tick marks.

Next the program sets the value of the variabvle "x" to the minimum X value in the m_Primatives collection and calls subroutine EvaluateExpression to evaluate the expression. It then loops over the desired X values, setting the X value in m_Primatives, calling EvaluateExpression, and graphing the result.

Private m_Primatives As Collection

' Graph the equation entered by the user.
Private Sub cmdGraph_Click()
Dim expr As String
Dim xmin As Single
Dim xmax As Single
Dim Dx As Single
Dim ymin As Single
Dim ymax As Single
Dim x As Single
Dim y1 As Single
Dim y2 As Single
Dim i As Integer

    On Error GoTo EvaluateError

    ' Make the primatives collection.
    Set m_Primatives = New Collection

    ' Get the bounds.
    xmin = CSng(txtXmin.Text)
    xmax = CSng(txtXmax.Text)
    Dx = CSng(txtDx.Text)
    ymin = CSng(txtYmin.Text)
    ymax = CSng(txtYmax.Text)

    ' Scale to fit the bounds.
    picGraph.Scale (xmin, ymax)-(xmax, ymin)

    ' Get the expression.
    expr = txtExpression.Text

    ' Draw the graph's background.
    picGraph.Line (xmin, 0)-(xmax, 0), vbBlue
    picGraph.Line (0, ymin)-(0, ymax), vbBlue
    For i = 0 To xmin Step -1
        picGraph.Line (i, -0.25)-Step(0, 0.5), vbRed
    Next i
    For i = 0 To xmax
        picGraph.Line (i, -0.25)-Step(0, 0.5), vbRed
    Next i
    For i = 0 To ymin Step -1
        picGraph.Line (-0.25, i)-Step(0.5, 0), vbRed
    Next i
    For i = 0 To ymax
        picGraph.Line (-0.25, i)-Step(0.5, 0), vbRed
    Next i

    ' Graph the equation.
    m_Primatives.Add xmin, "x"
    y1 = EvaluateExpression(expr)
    For x = xmin + Dx To xmax Step Dx
        ' Set the new value for x.
        m_Primatives.Remove "x"
        m_Primatives.Add x, "x"

        ' Evaluate.
        y2 = EvaluateExpression(expr)

        ' Draw the next line.
        picGraph.Line (x - Dx, y1)-(x, y2)

        ' Save the current Y value.
        y1 = y2
    Next x
    Exit Sub

    MsgBox Err.Description
End Sub
For information on how the program parses expressions, see Evaluate mathematical expressions using code.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.