Search code examples
javabigdecimalnumerical-analysis

Issue with Bigdecimal in java


I have to calculate the following function:

f(x)=x^3-x-1

I've created a class, named "Function" and inside of it, I have a method calculating the above function.

Here comes my code:

double function(double num)
{
    BigDecimal first,second;
    double a,b,c,b_copy;
    a = Math.pow(num, 3);
    b=(double)a-num;
    first=new  BigDecimal(b);
    second=new BigDecimal("1.0");
    first.min(second);
    b_copy=first.doubleValue();
    return b_copy ;
} 

I actually have some problems with these two lines of code:

    first.min(second);
    b_copy=first.doubleValue();

for example when num is 0 b_copy must be -1 but it is 0. Why is that?


Solution

  • the min(...) method returns a BigDecimal, it doesn't modify it. Try this:

    first = first.min(second);
    

    Also, if you want to subtract 1 from the value of first (as your formula indicates), use the subtract(...) method because min(...) actually returns the smallest values of the two BigDecimals.

    first = first.subtract(second);