1

I am trying to write a formula for one of my functions where I need to raise my X to power of Y. The values I am working with are really small and will get rounded up as soon as I use pow function of Math, BigInteger and BigDecimal.

For example if I use the following values it will return 1000 whereas it should return 1006.931669! T0 = 1000, TN = 1, k = 1, N = 1000

Formula

    double X = (finalTemp/initialTemp);
    double A = Math.pow(X, (k/n));
    double tk = initialTemp * A;
Siyavash
  • 970
  • 9
  • 23
  • 1
    Please show the code you're using – Lino Mar 27 '19 at 11:44
  • @Lino Code added! – Siyavash Mar 27 '19 at 11:46
  • 3
    I guess you have that problem because of how [Integer division works in java](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0). To fix your problem, you probably need *Floating point division* – Lino Mar 27 '19 at 11:48
  • first multiply all terms in the numerator then divide by denominator – uneq95 Mar 27 '19 at 11:49
  • Maybe this helps: https://stackoverflow.com/questions/16441769/javas-bigdecimal-powerbigdecimal-exponent-is-there-a-java-library-that-does – Astrogat Mar 27 '19 at 11:49
  • Did you try the type to float ? – Googlian Mar 27 '19 at 11:51
  • `pow` never rounds its return value. Your problem is due to integer rounding in either `finalTemp/initialTemp` or `k/n`. You probably stumbled across a specific case in which integer division gave the same results as floating point division. – meowgoesthedog Mar 27 '19 at 11:55
  • 3
    Duplicate of [Integer division: How do you produce a double?](https://stackoverflow.com/questions/3144610/integer-division-how-do-you-produce-a-double) – Socowi Mar 27 '19 at 12:11

2 Answers2

4

They are being divided in integer arithmetics. So dividing integer a by integer b you get how many times b fits into a, If the types of the operands are double, then "real" division is performed.

double X = (finalTemp/(double)initialTemp);
double A = Math.pow(X, (k/(double)n));
double tk = initialTemp * A;
One Man Crew
  • 9,420
  • 2
  • 42
  • 51
2

the output is correct according to calculator

public class Main
{
    public static void main(String[] args) {
        double finalTemp = 1.0;
        double initialTemp = 1000.0;
        double k = 1.0;
        double n = 1000.0;
        double X = (finalTemp/initialTemp);
        double A = Math.pow(X, (k/n));
        double tk = initialTemp * A;
        System.out.println(tk);
    }
}

output is 993.1160484209338

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125