VB co-ordinate calculation with NCalc

127 Views Asked by At

I need this to loop from -n to n but this only produces one co-ordinate so far. Does anyone know any easy quick fixes so I can have values from -n to n (step 1) subbed into the y equation id input?

I'm also not sure if I'm using the expression section correctly as I've never tried NCalc before today.

Dim y As String
Dim n As Integer

n = txtX.Text
y = txtY.Text
For x As Integer = -n To n Step 1

    Dim exp As Expression = New Expression(y)
    exp.Parameters("n") = n
    Label1.Text = exp.Evaluate

    Chart1.Series("plot1").Points.AddXY(x, y)
Next
1

There are 1 best solutions below

0
On BEST ANSWER

I looked at NCalc and managed to come up with the following.

On an empty form, I placed two textboxes, "tbEquation" to hold the equation, and "tbXextents" to hold the maximum x-value for evaluating the function; and a button "bnDrawGraph" to tell it to draw the graph.

Private Sub bnDrawGraph_Click(sender As Object, e As EventArgs) Handles bnDrawGraph.Click

    Chart1.Legends.Clear()
    Chart1.Series.Clear()
    Dim xy As New Series
    xy.ChartType = SeriesChartType.Line

    Dim expr = New NCalc.Expression(tbEquation.Text)
    Dim xMax = Integer.Parse(tbXextents.Text)

    For x = -xMax To xMax
        expr.Parameters("n") = x
        Dim y = Convert.ToDouble(expr.Evaluate())
        xy.Points.AddXY(x, y)
    Next

    Chart1.Series.Add(xy)

End Sub
  • You only need to create the expression once, before using it in the loop.
  • It seems that the Evaluate() method returns an Object rather than any particular type of variable, so I used Convert.ToDouble to get the value as a numeric type suitable for using in a chart series.

Sample output:

enter image description here