# BigInteger precision is lost in nashorn

XMLWordPrintable

#### Details

• Bug
• Resolution: Duplicate
• P3
• None
• 9
• None
• generic
• generic

#### Description

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++) {
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++) {
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.

#### People

Hannes Wallnoefer
Sundararajan Athijegannathan