-3

I calculated 10^10 using math.pow in java but it is returning 2147483647 but when i ask 10^9 it returns correct value. Why is this happening?? I did this by creating my own function also but now it is returning 1410065408. My function gave correct value for 10^9.

Why is java not calculating correct value of 10^10????

Someone explain this to me please.

  • 2
    What code did you use? – g00se Mar 11 '23 at 12:33
  • 1
    For me, `System.out.println(Math.pow(10, 10));` prints `1.0E10` – Abra Mar 11 '23 at 12:37
  • 1
    Computer arithmetic is not the same as real-world arithmetic. – undefined symbol Mar 11 '23 at 12:48
  • 1
    @Abra for me too. And that is correct. So Java *is* calculating the correct value. Nikhil Pal, please include a [mre] in your question. – Ole V.V. Mar 11 '23 at 13:26
  • 1
    Today’s tip: If you are programming, you need to train distinguishing between your observations and your assumptions. You saw an output of 2147483647 (observation). You assumed (in this case falsely) that `Math.pow()` had returned that value. Starting out by assuming that your programming cannot do what you are trying to do will not lead you far. Many find it hard at first but soon learn in case of unexpected output that the error is by all probability on their own side. That’s the starting point that I take and the colleagues that I consider professional. I encourage you to consider it too. – Ole V.V. Mar 11 '23 at 14:27

2 Answers2

2

Primitive types are stored in a finite number of bits. Integers are stored in 32 bits and thus have an upper bound of 2^31-1 or 2147483647. You might consider using a double (floating point) or a long (integer) to store numbers with 64 bits, that is up to 2^63-1, and if that isn't sufficient, then there are libraries that allow you to extend further this limit, such as BigInteger or BigDecimal.

By the way you might consider adding the code you tried so that people can see what you're doing exactly.

mi1000
  • 104
  • 9
1

Java primitive types have a constrained range. There is 32-bits of precision for integers and 64-bits for longs; if you want arbitrary precision use a BigInteger.

System.out.println(BigInteger.valueOf(10).pow(10));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249