0

我正在尝试构建一个表达式解析器来评估数学表达式的值。然而,问题在于某些类型的表达式,其计算结果为无理数。

让我们举一个例子,例如(√2)² 这应该评估为。2但是由于程序编码的逻辑,它返回一个小数点数。

首先√2评估哪个等于1.4142135,然后结果平方给出1.9999998

目前,所能做的就是将表达式通过JLink发送到Mathematica,然后使用结果。但是,这需要第三方软件的帮助。

我想知道这整个事情是否可以在java中实现。

4

2 回答 2

3

Yes, you can certainly implement an expression parser in Java. I think your fundamental error is not in Java programming but in program design.

You should not be evaluating surds until as late as possible. Instead you should be evaluating expressions like (sqrt(n))^2 to sqrt(n)*sqrt(n) and sqrt(n)*sqrt(n) to n. Only then should you consider converting n into an equivalent floating-point number.

What you have identified as an error in your approach is a feature of floating-point arithmetic which you will struggle to fight against. A better strategy is to work around it by implementing symbolic operations on symbolic expressions.

于 2012-11-22T15:35:03.537 回答
0
Double value = new Double(2);
Double power = new Double(2);
Double result = Math.pow(value, power);
result = Math.sqrt(result);
System.out.print(result);
于 2012-11-22T15:32:25.607 回答