Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8146264

BigInteger precision is lost in nashorn

    XMLWordPrintable

Details

    • Bug
    • Resolution: Duplicate
    • P3
    • None
    • 9
    • core-libs
    • None

    Description

      This bug was reported via nashorn-dev. See also http://mail.openjdk.java.net/pipermail/nashorn-dev/2015-December/005783.html

      The test cut-pasted here for convenience.

      Example of a Java function I would like to get working in Nashorn / jss javascript below:

        public static BigInteger fibonacci(int n) {
          BigInteger prev = new BigInteger("0");
          if (n == 0) {
            return prev;
          }
          BigInteger next = new BigInteger("1");
          if (n == 1) {
            return next;
          }
          BigInteger fib = null;
          int i;
          for (i = 1; i < n; i++) {
            fib = prev.add(next);
            prev = next;
            next = fib;
          }
          return fib;
        }

      We can test with these values:

      n=77: 5527939700884757
      n=78: 8944394323791464
      n=79: 14472334024676221

      So far so good. Now I try the - what I think is - equivalent function in
      javascript:

      function fibonacci(n) {
        var BigInteger = Java.type("java.math.BigInteger");
        prev = new BigInteger("0");
        if (n == 0) return prev;

        next = new BigInteger("1");
        if (n == 1) return next;

        var i, fib = null;
        for (i = 1; i < n; i++) {
          fib = prev.add(next);
          prev = next;
          next = fib;
        }
        return fib;
      }

      However, now we get different results:

      n=77: 5527939700884757
      n=78: 8944394323791464
      n=79: 14472334024676220

      Note that the value for n=79 is off by one.

      Attachments

        Issue Links

          Activity

            People

              hannesw Hannes Wallnoefer
              sundar Sundararajan Athijegannathan
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: