BigDecimal to the power of BigDecimal on Java/Android

后端 未结 4 1734
终归单人心
终归单人心 2020-12-07 01:43

I have a simple BigDecimal that I want to power to another BigDecimal, for example 11.11^-1.54. What would be the neatest way to do it in Java/Android? I don\'t like the ide

4条回答
  •  长情又很酷
    2020-12-07 02:09

    How many digits of precision do you need? You are only using 4 digits in your example. If this is medical and there for real world, you can only measure most things in the real world to 10-13 digits of accuracy and double has up to 16 digits of accuracy.

    System.out.println(Math.pow(11.11, -1.54));
    

    prints

    0.024524510581710988
    

    If you use a library from this book http://www.apropos-logic.com/nc/, you can get

    int runs = 10000;
    
    long start = System.nanoTime();
    double x1 = 0;
    for (int i = 0; i < runs; i++)
        x1 = Math.pow(11.11, -1.54);
    long time = System.nanoTime() - start;
    System.out.println(x1 + " took " + time / runs / 1e3 + " us avg.");
    
    long start2 = System.nanoTime();
    BigDecimal x2 = null;
    for (int i = 0; i < runs; i++)
        x2 = exp(ln(BigDecimal.valueOf(11.11), 20).multiply(BigDecimal.valueOf(-1.54)), 20);
    long time2 = System.nanoTime() - start2;
    System.out.println(x2 + " took " + time2 / runs / 1e3 + " us avg.");
    

    prints (us for micro-seconds)

    0.024524510581710988 took 0.478 us avg.
    0.02452451058171098739 took 603.769 us avg.
    

    with 40 digits of precision

    0.0245245105817109873886495555036930857940 took 1409 us avg.
    

    which may still be fast enough on your device.

    I haven't included the code, partly because its very long. I am impressed how fast it is. ;)

提交回复
热议问题