Reputation: 3521
I am trying to build an expression parser which evaluates the value of a mathematical expression. However the problem is for certain categories of expression which evaluates to an irrational number.
Lets take an example such as (√2)²
This should evaluate to 2
.However due to the logic the program is coded it returns a fractional point number.
First √2
is evaluated which equals 1.4142135
and then the result is squared giving 1.9999998
Presently, what all could do is to send the expression to Mathematica via JLink and then use the result. However this takes the help of a third party software.
I want to know if this whole thing can be implemented in java.
Upvotes: 0
Views: 355
Reputation: 78364
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.
Upvotes: 3
Reputation: 47310
Double value = new Double(2);
Double power = new Double(2);
Double result = Math.pow(value, power);
result = Math.sqrt(result);
System.out.print(result);
Upvotes: 0