Solved

math formula parsers

Posted on 2002-04-29
4
460 Views
Last Modified: 2010-04-04
hi does anyonw know a free math formula parser component? help! thanks! :)
0
Comment
4 Comments
 
LVL 14

Expert Comment

by:AvonWyss
ID: 6976744
You can find a bunch here:
http://www.torry.net/expressions.htm

For free ones, look at the entries markes with FW (Freeware) or FWS (Freeware with source).
0
 
LVL 6

Expert Comment

by:zebada
ID: 6978982
There's one here http://www.blacky.co.nz/free/index.htm
called Expr - about halfway down.

If that link is broken (it often is) then go to this link: http://www.geocities.com/freeblacky
Download the expr.zip file which is written in Delphi.
Note: the expression.zip is written in java not Delphi.

0
 

Author Comment

by:dabestprogrammerindauniverse
ID: 6979428
thanks! but actually, what i need is also a math formula evaluator that can also do summations :(
0
 

Accepted Solution

by:
Hamatoma earned 100 total points
ID: 7036002
Hi,

I have written this class, modify and/or use it!

unit HmLbCalc;

interface

uses
      Math, HmLbType;

type
      T_Operator = (opUndef,
            opPlus, opMinus,
            opTimes, opDiv, opModulo,
            opPower
            );

const
C_MaxFloatStack = 64;

type
T_FloatStack = class
      FStack: array [0..C_MaxFloatStack] of extended;
      FTop: integer;
      constructor Create;
      procedure Push (Val: extended);
      function Pop: extended;
      function Top: extended;
      function IsEmpty: boolean;
      end;

const
C_MaxOperatorStack = 64;

C_StdPrecision = -2;

type
T_OperatorStack = class
      FStack: array [0..C_MaxOperatorStack] of T_Operator;
      FTop: integer;
      constructor Create;
      procedure Push (Val: T_Operator);
      function Pop: T_Operator;
      function Top: T_Operator;
      function IsEmpty: boolean;
      function GetLevel: integer;
      end;

T_Calculator = class
      private
      FMemory: array [0..9] of extended;
      FResult: extended;
      FPrecision: integer;
      FExponentNotation: boolean;
      FOperandStack: T_FloatStack;
      FOperatorStack: T_OperatorStack;
      public
      constructor Create;
      function Expr (ExspectedEnd: char; const Line: string;
            var nPos: integer): T_ResultString;
      function FullExpr (const Line: string; var Val: extended): T_ResultString;
      function GetResult: extended; overload;
      function GetResult (Precision: integer): string; overload;
      function StrToOperator (const OpStr: string): T_Operator;
      function IsOperand (const Op: string; var Val: extended): boolean;
      function GetMemory (Ix: integer): extended;
      procedure PutMemory (Ix: integer; Val: extended);
      function Priority (Op: T_Operator): integer;
      function Reduce: T_ResultString;
      procedure SetPrecision (Digits: integer);
      procedure SetExponentNotation (Exponent: boolean);
      end; // T_Calculator
implementation

uses
      SysUtils,
      HmLbStr;

function NextExprToken (
      const Str: string;
      var StartIx: integer;
      var Token: string
      ): integer;
var
      Len, StrLen: integer;
      Dummy: extended;
begin
      StrLen := Length (Str);
      while (StartIx <= StrLen) and (Str [StartIx] <= ' ') do
            Inc (StartIx);

      Len := 0;
      if StartIx <= StrLen
      then case Str [StartIx] of
            '0'..'9':
                  Len := AToFloat (Str, StartIx, Dummy);
            'a'..'z', 'A'..'Z', '_':
                  begin
                  while (StartIx + Len <= StrLen)
                              and (Str [StartIx + Len] in ['0'..'9', 'a'..'z', 'A'..'Z', '_']) do
                        Inc (Len);
                  end;
            else
                  Len := 1;
            end; // case
      Token := copy (Str, StartIx, Len);
      Inc (StartIx, Len);
      Result := Len;
      while (StartIx <= StrLen) and (Str [StartIx] <= ' ') do
            Inc (StartIx);
end;

constructor T_FloatStack.Create;
begin
      FTop := -1;
end; // Create

procedure T_FloatStack.Push (Val: extended);
begin
      if FTop >= C_MaxFloatStack
      then raise Exception.Create ('T_FloatStack.Push: \berlauf bei '
            + IntToStr (C_MaxFloatStack));
      Inc (FTop);
      FStack [FTop] := Val;
end; // Push

function T_FloatStack.Pop: extended;
begin
      if FTop < 0
      then raise Exception.Create ('T_FloatStack.Pop: Unterlauf');
      Result := FStack [FTop];
      Dec (FTop);
end; // Push

function T_FloatStack.Top: extended;
begin
      if FTop < 0
      then raise Exception.Create ('T_FloatStack.Top: Unterlauf');
      Result := FStack [FTop];
end; // Top

function T_FloatStack.IsEmpty: boolean;
begin
      Result := FTop < 0;
end; // IsEmpty



//-------------------------------------------------------------------
constructor T_OperatorStack.Create;
begin
      FTop := -1;
end; // Create

procedure T_OperatorStack.Push (Val: T_Operator);
begin
      if FTop >= C_MaxOperatorStack
      then raise Exception.Create ('T_OperatorStack.Push: \berlauf bei '
            + IntToStr (C_MaxOperatorStack));
      Inc (FTop);
      FStack [FTop] := Val;
end; // Push

function T_OperatorStack.Pop: T_Operator;
begin
      if FTop < 0
      then raise Exception.Create ('T_OperatorStack.Pop: Unterlauf');
      Result := FStack [FTop];
      Dec (FTop);
end; // Push

function T_OperatorStack.Top: T_Operator;
begin
      if FTop < 0
      then raise Exception.Create ('T_OperatorStack.Top: Unterlauf');
      Result := FStack [FTop];
end; // Top

function T_OperatorStack.IsEmpty: boolean;
begin
      Result := FTop < 0;
end; // IsEmpty

function T_OperatorStack.GetLevel: integer;
begin
      Result := FTop;
end; // GetLevel


// --------------------------------------------------------------------
constructor T_Calculator.Create;
begin
      FResult := 0;
      FPrecision := -1;
      FOperandStack := T_FloatStack.Create;
      FOperatorStack := T_OperatorStack.Create;
end; // Create

function T_Calculator.StrToOperator (
      const OpStr: string
      ): T_Operator;
begin
      if OpStr = '+'
      then Result := opPlus
      else if OpStr = '-'
      then Result := opMinus
      else if OpStr = '*'
      then Result := opTimes
      else if OpStr = '/'
      then Result := opDiv
      else if OpStr = '%'
      then Result := opModulo
      else if OpStr = '^'
      then Result := opPower
      else Result := opUndef;
end; // StrToOp

function T_Calculator.IsOperand (
      const Op: string;
      var Val: extended
      ): boolean;
var
      Len: integer;
begin
      Result := true;
      if (Length (Op) = 2) and (Op [1] = 'M') and (Op [2] in ['0' .. '9'])
      then Val := GetMemory (ord (Op [2]) - ord ('0'))
      else begin
            Len := AToFloat (Op, 1, Val);
            Result := Len = Length (Op);
            end;
end; // IsOperand


function T_Calculator.Expr (
      ExspectedEnd: char;
      const Line: string;
      var nPos: integer
      ): T_ResultString;
var
      Token: string;
      Op1: extended;
      Op: T_Operator;
      Minus: boolean;
      LineLen: integer;
      Level: integer;
begin
      Level := FOperatorStack.GetLevel;
      Result := '';
      LineLen := Length (Line);

      repeat // until (Result <> '') or (nPos > LineLength);
            Minus := false;
            repeat
                  if NextExprToken (Line, nPos, Token) = 0
                  then break;
                  Op := StrToOperator (Token);
                  if Op = opMinus
                  then Minus := not Minus;
            until not (Op in [opMinus, opPlus]);

            if Token = ''
            then begin
                  Result := 'Operand erwartet';
                  break;
                  end;

            if Token = '('
            then begin
                  Result := Expr (')', Line, nPos);
                  Op1 := FOperandStack.Pop;
                  end // Token = Klammer
            else if not IsOperand (Token, Op1)
            then Result := 'Operand erwartet: ' + Token;

            if (Result <> '') or (Token = '')
            then break;

            if Minus
            then Op1 := - Op1;
            FOperandStack.Push (Op1);

            if (NextExprToken (Line, nPos, Token) = 0)
                  or (Token [1] in [')', ','])
            then break;

            Op := StrToOperator (Token);
            if Op = OpUndef
            then begin
                  Result := 'unbekanntes Rechenzeichen: ' + Token;
                  break;
                  end;
            while (Result = '') and not FOperatorStack.IsEmpty
                        and (Priority (FOperatorStack.Top) >= Priority (Op)) do
                  Result := Reduce;

            if (Result = '') and (nPos > LineLen) or (Line [nPos] = ')')
            then begin
                  Inc (nPos);
                  break;
                  end;
            FOperatorStack.Push (Op);
      until (Result <> '') or (nPos > LineLen);
      if (ExspectedEnd = #0) and (Token = '') or (Token = ExspectedEnd)
      then begin
            while FOperatorStack.GetLevel > Level do
                  Reduce;
            end
      else if ExspectedEnd = #0
            then Result := '<Eingabeende> erwartet statt: ' + Token
            else Result := ExspectedEnd + ' erwartet statt: ' + Token;
end; // Expr

function T_Calculator.FullExpr (
      const Line: string;
      var Val: extended
      ): T_ResultString;
var
      nPos: integer;
begin
      nPos := 1;
      Result := Expr (#0, Line, nPos);
      if (Result = '') and (nPos < Length (Line))
      then Result := 'Elemente nach Ausdrucksende: ' + copy (Line, nPos, 255)
      else begin
            FResult :=FOperandStack.Pop;
            Val := FResult;
            end;
end; // FullExpr

function T_Calculator.GetResult: extended;
begin
      Result := FResult;
end; // GetResult

function T_Calculator.GetResult (
      Precision: integer
      ): string;
var
      FormatStr: string;
begin
      if Precision = C_StdPrecision
      then Precision := FPrecision;

      if Precision < 0
      then FormatStr := '%g'
      else if FExponentNotation or (FResult > 1E16) or (FResult < -1E16)
            then FormatStr := '%.' + IntToStr (Precision + 1) + 'e'
            else FormatStr := '%.' + IntToStr (Precision) + 'f';
      Result := Format (Formatstr, [FResult])
end; // GetResult

function T_Calculator.GetMemory (Ix: integer): extended;
begin
      Result := FMemory [Ix];
end; // GetMemory

procedure T_Calculator.PutMemory (Ix: integer; Val: extended);
begin
      FMemory [Ix] := Val;
end; // PutMemory

function T_Calculator.Priority (
      Op: T_Operator
      ): integer;
begin
      case Op of
      opPlus, opMinus:
            Result := 1;
      opTimes, opDiv, opModulo:
            Result := 2;
      opProcent, opProcentPlus, opProcentMinus, opProcentFrom,
      opProcentPlusFrom, opProcentMinusFrom, opProcentBase:
            Result := 3;
      opPower:
            Result := 4;
      else
            Result := -1;
      end;
end; // Priority

function T_Calculator.Reduce: T_ResultString;
var
      Op1, Op2: extended;
      Op: T_Operator;
begin
      Result := '';
      Op2 := FOperandStack.Pop;
      Op1 := FOperandStack.Pop;
      Op := FOperatorStack.Pop;
      case Op of
      opPlus:      
            Op1 := Op1 + Op2;
      opMinus:      
            Op1 := Op1 - Op2;
      opTimes:      
            Op1 := Op1 * Op2;
      opDiv:      
            if Op2 = 0.0
            then Result := 'Division durch 0'
            else Op1 := Op1 / Op2;
      opModulo:
            if trunc (Op2) <= 0
            then Result := 'Modulus <= 0: ' + Format ('%f', [Op2])
            else Op1 := trunc (Op1) mod trunc (Op2);
      opPower:
            if Op1 < 0
            then Result := 'Basis < 0: ' + Format ('%f', [Op1])
            else Op1 := power (Op1, Op2);
      else
            Result := 'Unbekannter Operator: ' + IntToStr (ord (Op));
      end;
      if Result = ''
      then FOperandStack.Push (Op1);
end; // Reduce


                         
end.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question