4

Say,

base = 2 and e = 20000.5671

How to perform (base power e) for above example in java.

Clearly Math.pow(base, e) is not the way to go as it print's "Infinity"

and BigDecimal accepts 'e' of type int only.

Any other way to achieve this? Expecting more of a JDK library rather than 3p.

2 Answers2

7

You can try using exponent product rule.

ab+c = ab * ac

so you can raise 2 to the power of 20000 using the BigDecimal function then multiply by 2 raised to the power 0.5671

Note :-

This approach will produce an answer that will only be correct to the precision of the least of its parts. The Math.pow function returns a double, and so is only accurate to around 15 significant figures.

Aaron Hayman
  • 525
  • 3
  • 11
  • No! it's not possible as `^` only applies to ints – Vinay Prajapati Nov 06 '19 at 09:47
  • @VinayPrajapati is expressing power, not verbatim code. he knows a function that can do this – Aaron Hayman Nov 06 '19 at 09:49
  • 3
    Seems to work, although it's difficult to verify for those large numbers: `BigDecimal.valueOf(b).pow((int) e).multiply(BigDecimal.valueOf(Math.pow(b, e % 1)));` – tobias_k Nov 06 '19 at 09:52
  • can someone explain `^` as bitwise OR. I tried ~aaron's solutions. – Vinay Prajapati Nov 06 '19 at 09:55
  • 2
    @VinayPrajapati That is not Java. Aaron explains the math, and is using math notation, assuming that OP will be able to translate that to proper Java. – tobias_k Nov 06 '19 at 09:58
  • 2
    @tobias_k You can give the output a sanity check using similar maths tricks. 2^20000.5671 is the same as 10^(log_10(2)*20000.5671). log_10(2)*20000.5671 = 6020.770627. Then using the trick in the answer 10^0.770627 is around 5.89594. So the answer should be in the region of 5.89594E+6020. p.s. thanks for the edit. – Aaron Hayman Nov 06 '19 at 15:15
1

So, there is a mathematical workaround:

BigDecimal.valueOf(2).pow(20000).multiply(BigDecimal.valueOf(Math.pow(2, .5671)))
Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86