Grasshopper

algorithmic modeling for Rhino

VB, C# how to evaluate a mathematical expression as a string written in VB or C# style

Hi, 

I have to take an expression as a string (written in proper VB or C# syntax) and evaluate it within a component using x,y,z values. Seems much more difficult than I thought. Any idea is very much appreciated. 

Say for instance I have F=Math.Sqrt(Math.Abs(x*y*z))

as a string input and I have x,y,z values

I want to let users change the F input to anything they want. The expression above is just an example. 

Views: 1435

Replies to This Discussion

You can write your own math parser (complex) or use an existing one (e.g. NCalc).

Another possibility is to compile the expression at runtime (Python, C#/VB). Keep in mind that the user can enter any kind of code.

Greetings!

May I ask a question? Why do you need to write your own math parser when there is already one in GH? I'm not asking to be difficult, but because I am curious.

Because 2^2^3 is NOT 64

You don't have to write your own parser and of course you still can use the parser provided by Grasshopper:

var parser = new Grasshopper.Kernel.Expressions.GH_ExpressionParser();
parser.AddVariable("x", x);
parser.AddVariable("y", y);
parser.AddVariable("z", z);
result = parser.Evaluate(f);

Just keep in mind that the power function has this little bug.

Cheers!

Attachments:

Thanks for your prompt complete response!!! 

Did it with a bit of optimization. In case anybody needs in future:

Dim vals(P.count-1) As Double
Dim CorrectExpression = Grasshopper.Kernel.Expressions.GH_ExpressionSyntaxWriter.RewriteAll(F)
Dim Expr As New Grasshopper.Kernel.Expressions.GH_ExpressionParser()
Expr.CacheSymbols(CorrectExpression)
Dim k As Integer
For Each v As point3d In P
Expr.ClearVariables
Expr.AddVariable("x", V.x)
Expr.AddVariable("y", V.y)
Expr.AddVariable("z", V.z)
vals(k) = Expr.Evaluate(Expr.CachedSymbols())._Double
k += 1
Next
E = Vals

Cheers, Pirouz

RSS

About

Translate

Search

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service