Execute BigDecimal applet example
Java code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math.*;
import java.math.BigInteger;
import java.math.BigDecimal;
public class BigDecEx extends JApplet implements ActionListener{
JLabel lN1, lN2, lP;
JTextField tN1, tN2, tP;
JButton btnAdd,btnSub,btnMul,btnDiv,btnSqrt,btnClear; JTextArea outArea;
public void init(){
Box box=Box.createVerticalBox();
// input
lN1=new JLabel("Input first number"); box.add(lN1);
tN1=new JTextField(100); tN1.setEditable(true); box.add(tN1);
lN2=new JLabel("Input second number"); box.add(lN2);
tN2=new JTextField(100); tN2.setEditable(true); box.add(tN2);
lP=new JLabel("Precision of results"); box.add(lP);
tP=new JTextField(20); tP.setText("200");
tP.setEditable(true); box.add(tP);
// buttons
btnAdd=new JButton("+"); btnAdd.addActionListener(this); box.add(btnAdd);
btnSub=new JButton("-"); btnSub.addActionListener(this); box.add(btnSub);
btnMul=new JButton("*"); btnMul.addActionListener(this); box.add(btnMul);
btnDiv=new JButton("/"); btnDiv.addActionListener(this); box.add(btnDiv);
btnSqrt=new JButton("sqrt"); btnSqrt.addActionListener(this); box.add(btnSqrt);
btnClear=new JButton("Clear"); btnClear.addActionListener(this); box.add(btnClear);
// Output
String desc="This is a rudimentary arbitrary precision decimal calculator\n";
outArea=new JTextArea(desc,30,60);
ScrollPane scrollPane=new ScrollPane();
scrollPane.add(outArea);
box.add(scrollPane);
Container c=getContentPane();
c.add(box);
setSize(600,300);
setVisible(true);
showStatus("Enter operands and operator");
}
public BigDecimal bSqrt(BigDecimal N, int nP){
// Example: sqrt(2) to 20,000 decimal places required 11 iterations in 68 seconds.
if(N.signum()<=0)return BigDecimal.ZERO; // return zero for neg. arguments
double x=java.lang.Math.sqrt(N.doubleValue());
BigDecimal X1=new BigDecimal(x); // Initial approximation
BigDecimal X=BigDecimal.ZERO;
int count=0, maxCount=0,nP1=nP;
// maxCount is max. number of iterations, where 16*2^maxCount>=nP
for(maxCount=0;maxCount<1000;maxCount++){nP1/=2;if(nP1==0)break;}
BigDecimal residue=BigDecimal.ONE;
while(residue.compareTo(BigDecimal.ZERO)!=0 && count