Reputation: 321
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?
Upvotes: 2
Views: 101
Reputation: 121998
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.
Upvotes: 4
Reputation: 22474
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);
Upvotes: 4