Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase ««12345»»»

A simple math expression solver Expand / Collapse
Author
Message
Posted Monday, November 21, 2011 11:24 AM
SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, October 14, 2014 1:17 PM
Points: 1,868, Visits: 481
You earler post had a commet about the function only handles one expression at a time. That was kind of the point. In a select statement the function could be called for multiple expressions. That is actually the case in my situation. A table column contains a simple math expression. So using a function would allow me to get the answer to as many lines as would get returned in the select statement.

Thanks for your posts.

Ben
Post #1209533
Posted Monday, November 21, 2011 12:17 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Monday, January 7, 2013 2:28 PM
Points: 51, Visits: 158
The method for evaluating algebraic equations is properly done through the use of reverse polish notation or more formally known as postfix notation. (It's referred to a reverse Polish notation because a Polish fellow figured it out) I've written these programs in COBOL, never thought about doing it in in T-SQL, maybe VB.NET. Could be a challenge. Through the use of cursors it might not be that difficult. I'll see if I can come up with something in a few days. You can use this method with a few modifications to evaluate formal logic as well. i.e is (A > B) or (C > B & D = B) a true statement. That can get very complex, trust me. So can algebra.
Post #1209585
Posted Monday, November 21, 2011 12:26 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Monday, January 7, 2013 2:28 PM
Points: 51, Visits: 158
My earlier post was used in a software package to evaluare formulas in a table. The table was comprised of three "columns". The first column had the user friendly version of the forumla, the second column had the postfix form of that equation, the third was a key field used by an evaluation program to find the proper formula. The the evaluater program would read the table based on the key column and evaluate the second column streight away. Prettly slick, really.

When I say user friendly think of (a + b) / c. I don't have access to my programs right now to show the exact form of that in postfix but t is something like: c!/!a!b!+ (the ! is used as a separator similar to a , in a .csv file). To get the user friendly formula into postfix you have to use stack processing which lends itself to cursor processing (I think).
Post #1209595
Posted Monday, November 21, 2011 12:27 PM
SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, October 14, 2014 1:17 PM
Points: 1,868, Visits: 481
I would stay away from cursors if you decide to do it in t-sql. It might be better to use vb.net or c# and then use the clr. Although I believe you could still use a recursive function call if you were able to properly parse the equation.

Ben
Post #1209596
Posted Monday, November 21, 2011 12:33 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Monday, January 7, 2013 2:28 PM
Points: 51, Visits: 158
The key to this method is the formulas have already been converted to postfix notation and all the evaluator function has to do is peddle down the string evaluating the variables as you go and then applying the op code (+ - * /,etc.) to the variable. If you use an HP12c calculator you would be familiar with postfix notation. Formulas are generally pre-thought out and entered via key strokes. Once the operator exits that field the program would immediately format the formula into postfix noation ready for the processing program to select it and evaluate it. You have to think how something like this would be used. At a data entry level you don't have to worry about speed.
Post #1209600
Posted Monday, November 21, 2011 1:28 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, September 10, 2014 12:52 PM
Points: 3, Visits: 19
I wonder if it would be fair to call this code a simplified RPN processor. Essentially you are taking infix notation and putting into a form that used to be required on some calculators.
Post #1209623
Posted Monday, November 21, 2011 1:33 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Monday, January 7, 2013 2:28 PM
Points: 51, Visits: 158
Sort of. The code for evaluating a simple formula like mentioned early in this thread could be called a simplified RPN evaluator, I guess. I really didn't spend much time on it because I know intemately what an RPN process is all about. A real RPN processor can evaluate any depth algebraic equation.
Post #1209624
Posted Monday, November 21, 2011 1:53 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Tuesday, June 17, 2014 4:40 PM
Points: 5, Visits: 63
------considering execution for many rows-----------------

DECLARE @ExprCollection Table(expr VARCHAR(100) )

INSERT INTO @ExprCollection(expr)
SELECT '2+1'
UNION ALL
SELECT '5*2'
UNION ALL
SELECT '6/3'

DECLARE @genSql AS VARCHAR(MAX)

CREATE TABLE #ExpValueTable ([value] INT,[Id_Exp] [VARCHAR](100) PRIMARY KEY)

SELECT @genSql = CASE WHEN @genSql Is Null
THEN ' INSERT INTO #ExpValueTable ([value],[Id_Exp]) ' + ' SELECT ' + expr + ' AS ExpValue,''' + expr +''' As Exp'
ELSE @genSql + ' UNION SELECT ' + expr + ' AS ExpValue,''' + expr +''' As Exp' END
FROM @ExprCollection
GROUP BY expr

EXEC(@genSql)

SELECT *
FROM #ExpValueTable

--- OR JOIN YOUR TABLE TO THE TEMPORARY TABLE... AND BETTER USING THE TABLE PRIMARY KEY

DROP TABLE #ExpValueTable
Post #1209630
Posted Monday, November 21, 2011 2:20 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Monday, January 7, 2013 2:28 PM
Points: 51, Visits: 158
In this example the size of the table of literals is unlimited. However aditional coding is needed tu use variable names i.e. A, B, C, etc. A little fooling around with this thing and it might serve the most elementary uses.

DECLARE @ExprCollection Table(expr VARCHAR(100) )

INSERT INTO @ExprCollection(expr)
SELECT '2+1'
UNION ALL
SELECT '5*2'
UNION ALL
SELECT '6/3'

drop table #ExpValueTable
CREATE TABLE #ExpValueTable ([value] decimal(18,4),[Id_Exp] [VARCHAR](100) PRIMARY KEY)
declare ExprCursor cursor
for
select * from @ExprCollection

declare @Expr as varchar(100), @SQL varchar(max)

open ExprCursor
fetch next from ExprCursor into @Expr

while @@Fetch_Status = 0
BEGIN
set @SQL = ' INSERT INTO #ExpValueTable ([value],[Id_Exp]) SELECT ' + @expr + ' AS ExpValue,''' + @expr +''' As Exp'

fetch next from ExprCursor into @Expr

exec (@SQL)
END

close ExprCursor
deallocate ExprCursor


select * from #ExpValueTable
Post #1209642
Posted Monday, November 21, 2011 4:46 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, October 14, 2014 5:18 PM
Points: 13, Visits: 28
When I ran Ben's code, I had some problems if I didn't leave spaces between the operators and the values. i.e., fn_simplemath('3 - 4') worked while fn_simplemath('3-4') failed... I suspect this would require a minor tweaking of some of the substring arguments. But trying to debug a recursive function can be a bit troublesome.

It also occurred to me that since were were not concerned with operator precedence and simply calculating from left to right, we should be able to simply loop through the string without needing to be recursive.

My approach was to create a string that duplicates the input except for replacing all the "acceptable" operator values with a single unique character, in my case I used a tilde(~). This second string can then be used to identify the position of all the operators in the original string and make it easier to parse out the individual operand values

Here is my code:


CREATE Function [dbo].[fn_simplemath2]
( @Expression1 varchar(255))
returns numeric(18,6)
As
BEGIN
--
-- @Expression2 will duplicate @Expression1 with all operators replaced with ~
Declare @Expression2 varchar(255)
Set @Expression2 =
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Expression1,'-','~'),'+','~'),'*','~'),'/','~'),'%','~')
--
-- Local variables
Declare @PrevOpLoc int -- Location of previous operator
Declare @NextOpLoc int -- Location of next operator
Declare @OpChar Char(1) -- Current operator character
Declare @Result numeric(18,6) -- Hold running calculation and final return value
Declare @NextVal numeric(18,6) -- the next substring value to be used to modify result base on operator
--
-- Find the first operator
Set @NextOpLoc = CHARINDEX('~',@Expression2)
--
-- Initialize @Result to the first substring, If there are no operators, move entire string to @Result
Set @Result =
CASE
When @NextOpLoc = 0 then CAST(@Expression1 as numeric(18,6))
Else CAST(LEFT(@Expression1,@NextOpLoc-1) as numeric(18,6))
END
--
-- Now we will loop until we run out of operators
While @NextOpLoc <> 0
BEGIN
-- Get the actual operator from @Expression1, pull out the next substring value
Set @OpChar = SUBSTRING(@Expression1,@NextOpLoc,1)
Set @PrevOpLoc = @NextOpLoc
Set @NextOpLoc = CHARINDEX('~',@Expression2, @NextOpLoc + 1)
Set @NextVal= Cast(
SUBSTRING(@Expression1,@PrevOpLoc+1,
Case
When @NextOpLoc = 0 then LEN(@Expression1)
Else @NextOpLoc-1
End
- @PrevOpLoc) as numeric(18,6))
--
-- Perform the appropriate operation
Set @Result =
Case @OpChar
When '-' then @Result - @NextVal
When '+' then @Result + @NextVal
When '*' then @Result * @NextVal
When '/' then @Result / @NextVal
When '%' then @Result % @NextVal
Else null
End
END
Return @Result
END
Post #1209726
« Prev Topic | Next Topic »

Add to briefcase ««12345»»»

Permissions Expand / Collapse