java 数字表达式,数学表达式(字符串)到Java中的数字

I'm trying to find something like Java Embedding Plugin (JEP) that can evaluate a mathematical formula (string) and give back the answer.

But it should also calculate a variable, for example: (25+36+x)*2 = 25 should give: x = -11

A little like http://www.wolframalpha.com/, but it shouldn't be that versatile, and it should work off-line.

Open source is preferred.

I need it for my little calculator project, http://sourceforge.net/projects/calex/.

解决方案

This is called Arithmetic evaluation. One of the easiest way to implement this is using Edsger Dijkstra Shunting-yard_algorithm.

The shunting-yard algorithm is a

method for parsing mathematical

equations specified in infix notation.

It can be used to produce output in

Reverse Polish notation (RPN) or as an

abstract syntax tree (AST). The

algorithm was invented by Edsger

Dijkstra and named the "shunting yard"

algorithm because its operation

resembles that of a railroad shunting

yard. Like the evaluation of RPN, the

shunting yard algorithm is

stack-based. Infix expressions are the

form of mathematical notation most

people are used to, for instance 3+4

or 3+4*(2−1). For the conversion there

are two text variables (strings), the

input and the output. There is also a

stack that holds operators not yet

added to the output queue. To convert,

the program reads each symbol in order

and does something based on that

symbol.

But I have seen exact solution what you are looking for on some stackoverflow user blog, but I can't remember the address (it was like 'code monkeyism'). It was lightweight class, that you could use in applets (you could also define constants and reset values).

A Linear-Recursive Math Evaluator

This math expression evaluator was born out of a need to have a small-footprint and efficient solution which could evaluate arbitrary expressions reasonably efficiently without requiring pre-compilation. I needed something which would do basic math with variables, expressions like: "Top+2", "Bottom-2" and "(Right+1-Left)/2".

Research on the Internet turned up a number of fairly good solutions, all of which revolved around creating parse trees (which makes sense). The problem was - they were all rather bulky, and I couldn't afford to add 100K to my applet size just for math. So I started wondering about a linear recursive solution to the problem. The end result is an acceptably performing single class with no external dependencies, weighing in under 10 KiB.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值