1

I used jeval for some data computing tasks, and found a loss of accuracy. Is there any way to avoid accuracy loss while using jeval? I want to get the accurate result just like BigDecimal.

public class EvalTest {

    private static Evaluator eva = new Evaluator();

    public static void main(String[] args) {

        try {
            String formula = "780.0000000-259.9999998";
            String res = eva.evaluate(formula);

            BigDecimal a = BigDecimal.valueOf(780.0000000);
            BigDecimal b = BigDecimal.valueOf(259.9999998);
            BigDecimal c = a.subtract(b);

            System.out.println("a");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If I use jeval, the formula "780.0000000-259.9999998" will get an result as "520.0000001999999", but if I use BigDecimal, I can get the accuracy result "520.0000002".

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
lulijun
  • 415
  • 3
  • 22
  • 1
    I guess that `jeval` uses `double`. You should trust to `BigDecimal` results. – dehasi Mar 13 '19 at 14:51
  • But the reason I use jeval is I have scenarios which are much more complicateble than "780.0000000-259.9999998", like "(1+2)/3*4+5/6". jeval is a very convenient component for Mathematical operations. – lulijun Mar 13 '19 at 14:56
  • @lulijun: it may be very convenient, but if you can't make it use BigDecimals, it simply won't deliver the results you want. You will have to live with a certain degree of inaccuracy. – Rudy Velthuis Mar 13 '19 at 16:54

1 Answers1

1

According to Jeval's Javadoc for the evaluate(String expression) method for Jeval 0.9.4, it says:

"The result of the evaluated. expression. Numbers are treated as doubles, so resulting numbers will contain at least one decimal place."

You can't avoid accuracy loss when using doubles. See this. Floating point numbers have this limitations. For example, you can see it for simple expressions like 5.6 + 5.8, which yields 11.399999999999.

diogenesgg
  • 2,601
  • 2
  • 20
  • 29