Click to See Complete Forum and Search --> : calaculating an equation within a string
gilllyo
Feb 2nd, 2001, 04:13 AM
I'm trying to write a program that can manipulate equations supplied by the user. The only way to do this is put the equation as a string. But i need to calculate the equation. Some people have suggested using MS Script Control but that hangs my program when I use it.
Does any one know of an alternative?
HarryW
Feb 2nd, 2001, 05:29 AM
The problem with evaluating standard expressions (like (3+2-(5*3+1))/6) is that they are in infix notation, meaning that the operators go between the numbers they are operating on. This means you need to specify operator precendence to eliminate ambiguity. One of the best ways to tackle this problem is to convert the infix to either prefix (also called Polish, the above expression would be (/-+3 2+*5 3 1 6) ) or postfix (also called Reverse Polish, the ablove expression would be (3 2+5 3*1+-6/) ).
The general standard nowadays is to use Reverse Polish to evaluate expressions. You can they use a stack to perform the operations quite easily. you parse throught the string adding values to the stack, and when you encounter an operator you apply the operator to the topmost values on the stack (removing them from the stack) and put the resulting value back on the stack.
You can convert from infix to postfix quite easily, also using a stack.
I'm not sure how you would convert from postfix back to infix, but it should be possible.
This may not be relevant to what you're trying to do of course, but I don't really know what you're trying to do with the equations.
kedaman
Feb 2nd, 2001, 07:18 AM
Don't waste time creating a numeric expression evaluating algoritm, I suggest you use MS Script Control as the other did. Place one on the form, and then 3 textboxes, paste this code:
Private Sub Text1_Change()
On Error Resume Next
Text2 = ScriptControl1.Eval(Text1)
If Err Then Text3 = Err.Description Else Text3 = "OK"
End Sub
Run, and now you're able to enter whatever numeric expression you use in vb, for instance:
1+sin(-4.4)^(5-asc("B"))\4/5 and 4 xor len("Hello")
Guv
Feb 2nd, 2001, 11:19 AM
(X + 7) Mod ten is a simple substitution if X is a decimal integer. 0-2 become 7-9 and 3-9 become 0-6. You can reverse this by simple substitutuion or with If-Then-Else and some simple arithmetic.If EncryptDigit > 6 then
ClearDigit = EncryptDigit - 7
Else
Cleardigit = EncryptDigit + 3
End If
jmcswain
Feb 23rd, 2001, 08:42 PM
My faithful reference of over a decade has a recursive descent parser in the chapter titled "Expression Parsing and Evaluation." It's easy enough to convert to VB. See if Amazon has it:
Advanced C
Second Edition
Written by Herbert Schildt
Published by Osborne McGraw-Hill
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.