Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal to the power of BigDecimal on Java/Android

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 idea of converting to doubles because it is for a medical application, so I would appreciate the biggest presicion possible. So far I have reviewed http://commons.apache.org/math/ and math stuff from Google Guava, but found nothing.

Edit: The whole calculation is complex, and has many operations like this. I need as much precision at the end as possible.

like image 315
Elchin Avatar asked Aug 07 '12 15:08

Elchin


People also ask

How do you scale BigDecimal?

scale() is an inbuilt method in java that returns the scale of this BigDecimal. For zero or positive value, the scale is the number of digits to the right of the decimal point. For negative value, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

Can we convert BigDecimal to double in Java?

math. BigDecimal. doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.

Can we convert BigDecimal to string in Java?

The java. math. BigDecimal. toString() method is used to represent the current BigDecimal by which this method is called into String form, using scientific notation if an exponent is needed.


2 Answers

A utility class for BigDecimal https://github.com/tareknaj/BigFunctions

Example for z = x^y --> z = exp ( ln(x) * y )

final int SCALE = 10;
BigDecimal x = new BigDecimal(1);
BigDecimal y = new BigDecimal(12);

BigDecimal z = BigFunctions.exp( BigFunctions.ln(x, SCALE).multiply(y),SCALE );
like image 99
softawareblog.com Avatar answered Oct 21 '22 09:10

softawareblog.com


Look into "Java Number Cruncher: The Java Programmer's Guide to Numerical Computing" - Chapter 12.5 Big Decimal Functions : there is some source code with as exact as possible algorithm to compute exponential and logarithm.

Using the mathematical formula : x^y=exp(y*ln(x)) you can achieve a result with maximum precision.

Nevertheless doubles do have a good precision and I strongly recommand you test if it's not precise enough for your need.

like image 33
Laucia Avatar answered Oct 21 '22 07:10

Laucia