Saturday, 24 October 2020

A tokenizer that can recognize simple mathematical expressions

Introduction

Here is a finite state machine(FSM) that can recognize integers and floating point numbers as well as mathematical expressions including operators: +, -, *, /, ^ and brackets. However, negative sign and mathematics functions such as sine and logarithms cannot be handled by this machine.

Example

3+4, 2-7^2, 3.1416*9^2/14, (2.18+15.7)/2, ...

You may try to input some mathematical expressions below to see the results

Trial Input


Result
(,4,^,2,+,5,^,2,),^,(,1,/,2,),-,3

Amendment (2/5/2023)

There are some defects found in the above FSM which lead to undetected erroneous cases. For example, expressions such as (3+4)52, (3+4).52 and (3+4.2)52 are accepted by the algorithm. However, the source code given below have not solved this issue. The final solution for fixing the problem can be found in later post.


Source Code

No comments:

Post a Comment