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

标签 java parsing formula evaluate mathematical-expressions

我正在尝试查找类似 Java Embedding Plugin 的内容(JEP),可以评估数学公式(字符串)并返回答案。

但它还应该计算一个变量,例如:(25+36+x)*2 = 25 应该给出:x = -11

有点像http://www.wolframalpha.com/ ,但它不应该那么通用,它应该可以离线工作。

首选开源。

我的小计算器项目需要它,http://sourceforge.net/projects/calex/ .

最佳答案

这称为算术求值。实现这一点的最简单方法之一是使用 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.

但是我在一些 stackoverflow 用户博客上看到了您正在寻找的确切解决方案,但我不记得地址了(这就像“代码猴子主义”)。它是轻量级类,您可以在小程序中使用(您还可以定义常量和重置值)。

编辑:找到它:http://tech.dolhub.com/Code/MathEval

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.

关于java - Java中的数学表达式(字符串)到数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4173623/

相关文章:

java - 我如何使用 jemmy 测试应用程序退出

java - 优化 A* 算法

java - 如何在 Java Android Studio 中验证日月和年,

java - 为什么我的代码不工作(java netbeans)?

java - 在现有字符串之间添加新字符串

java - 如何防止 double 四舍五入到小数点后两位

java - 在java中使用Gson解析JSON数组/对象

parsing - Attoparsec:跳过(但不包括)多字符分隔符

r - 如何将字符串作为变量传递给 felm 回归

r - 如何在基本 R 公式中使用类似 quosure 的语法?