I have a question about an error when translating the pseudo code below into Java. There is no problem with the loss of accuracy because of truncation but a programming language issue that I can't seem to find.
I though the answer would be that the result of Math.pow()
would be too much for a double (range from 4.94065645841246544e-324d
to 1.79769313486231570e+308d
. But apparently there is more wrong and I can't see it.
PSEUDO CODE
x = 7.0
y = x^1000.0
n = y truncated to an integer
converted to
JAVA
double x, y;
int n;
x = 7.0;
y = Math.pow(x,1000.0);
n = (int)y;
Much appreciated, I'd really like to understand the issues here.
When you do,
double x = 7.0;
double y = Math.pow(x, 1000.0); // <-- INFINITY
you do exceed the precision of double
and you get Double.POSITIVE_INFINITY
System.out.println(y);
Output is
Infinity
When you cast that to int
you get Integer.MAX_VALUE
which is 2^31-1 or 2147483647. If you want to get a more convincing result you could use BigInteger
like
int n = BigInteger.valueOf(7).pow(1000).intValue();
System.out.println(n);
Output is
432069569
Of course, the real result is obtained by
System.out.println(BigInteger.valueOf(7).pow(1000));
Which results in a very big number indeed.