Java Reference
In-Depth Information
Table22-2
ArithmeticMethodsinBigDecimalClass(continued)
multiply(BigDecimalval)
ReturnsaBigDecimalwhosevalueistheproductofthe
argumentandtheoperand
negate()
ReturnsaBigDecimalwhosevalueistheoperandtimes-1
intsignum()
Returns-1,0,or1ifthevalueoftheBigDecimaloperand
isnegative,zero,orpositive
subtract(BigDecimalval)
ReturnsaBigDecimalwhosevalueisthedifference
betweentheargumentandtheoperand
Notein Table22-2 thatthearithmeticoperationsprovidedfor
BigDecimal numbers include addition, subtraction, multiplication, divi-
sion, absolute value, maximum, minimum, sign extraction, and negation.
A sample program
The following program demonstrates arithmetic on big decimal numbers
by calculating the square root. The code requests user input for a string of
digitsrepresentingthenumberandforthenumber'sscale.Thesquareroot
oftheuser'sinputiscalculatedusingNewton'smethodandtheresultsare
displayed on the screen. The following is a listing of the source code.
class BigDSqrt
{
public static void main(String[] args)
{
double value = 1.0;
String numS;
int scale = 30;
BigDecimal v;
System.out.println("Big decimal square root routine\n");
numS = Keyin.inString("Enter value: ");
scale = Keyin.inInt("Enter scale: ");
// Convert value to big decimal format
v = new BigDecimal(numS);
System.out.println(sqrt(v, scale));
}
public static BigDecimal sqrt(BigDecimal n, int s)
{
BigDecimal TWO = BigDecimal.valueOf(2);
// Obtain the first approximation
BigDecimal x = n.divide(BigDecimal.valueOf(3), s,
BigDecimal.ROUND_DOWN);
BigDecimal lastX = BigDecimal.valueOf(0);
// Proceed through 50 iterations
Search WWH ::




Custom Search