简体   繁体   中英

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?

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 BigDecimal s.

first = first.subtract(second);

BigDecimal class is immutable. You cannot change, once it created.

When you change that object, it always returns a new Object.

first=new  BigDecimal(b);  //  you created an object
second=new BigDecimal("1.0");
first.min(second); // you just modifying it. Hence a new object returned and you never received.

To receive the newly created object, you can write

first = first.min(second); 

When you write this, you are assigning the first with modified BigDecimal back

Not only min() , if you perform any operation on BigDecimal you need to reassign it back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM