Tratamento Casa Decimal

Olá pessoal, boa noite!

Estou estudando Cálculo Numérico, e estou aqui tentando fazer um algoritmo para fazer o calculo de aproximação de raízes, utilizando o método de Newton-Raphson.

Para tal, é necessário fazer várias iterações ( Xo…Xn), portanto, preciso utilizar casas decimais. Eu declarei uma variável double, mas está estourando. Eu preciso apenas utilizar os 5 primeiros números, alguém poderia me informar que método utilizar, queria fazer algo melhor do que ter que converter variável para String e realizar o tratamento.

Eu utilizei um substring(); porém não funciona para substring(0,6) pois em alguma itereção dá problema:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.substring(String.java:1934)
at javaapplication3.Main.main(Main.java:28)
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)


package javaapplication3;


public class Main {

    public static void main(String[] args) {


		Double fx, fxd, xx;

                Double xo, xod;
                String v1, v2, a, b;
                xo = - 0.5;
                xod = - 0.5;


                for(int i = 0; i <= 5; i++) {
                //calculo da f(x)
                        fx = 4*(Math.pow(xo,5)) - 7*(Math.pow(xo,2)) + 2;
                        v1 = fx.toString();
                        a = v1.substring(0, 4); //pegando apenas 4 casas decimais
                        xo = fx.valueOf(a);

                //calculo da f'(x)
                        fxd = 20*(Math.pow(xod,4)) - 14*xod;
                        v2 = fxd.toString();
                        if(v2.length()>4) {
                            b = v2.substring(0, 5);
                            xod = fxd.valueOf(b);
                        } else xod = fxd.valueOf(v2);
                       


               //calculo x+1
                    xx = xo - (xo/xod);

                       System.out.println("i: " + i + " | Xi: " + xo + " | f(xi): " + fx + " | f`(x1): " + fxd + " | x+1: " + xx);
                }

        }
  }

CONSOLE:

run:
i: 0 | Xi: 0.12 | f(xi): 0.125 | f(x1): 8.25 | x+1: 0.10545454545454545 i: 1 | Xi: 1.89 | f(xi): 1.8992995328 | f(x1): 92534.578125 | x+1: 1.8899795750751074
i: 2 | Xi: 73.4 | f(xi): 73.46013197959998 | f(x1): 1.466342220963875E21 | x+1: 23.331787175989085 i: 3 | Xi: 8.52 | f(xi): 8.521937977536963E9 | f(x1): 71.85343024672 | x+1: 8.401419624217118
i: 4 | Xi: 1790.0 | f(xi): 179073.86634721278 | f(x1): 5.3301111547012484E8 | x+1: 1454.1651031894935 i: 5 | Xi: 7.35 | f(xi): 7.3506398737171296E16 | f(x1): 16066.6919842 | x+1: 7.3495425121374325
CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo)

Se você mostrar isto a seu professor, ele vai ver claramente que não é seu. Então leia o código abaixo e entenda como é que ele quis que você trate as casas decimais. Dica: NÂO TEM NENHUMA CONVERSÃO PARA STRING no cálculo.
EDIT - como o Marcos Lima ressaltou, use java.lang.Double apenas quando necessário. Em cálculo, use sempre o primitivo double mesmo. No exemplo abaixo, não cheguei a usá-lo (apenas usei o método Double.parseDouble).

// NewtonRaphson.java
package guj;

import javax.swing.DefaultListModel;

interface Funcao {
    double f(double x);

    double df(double x);
}

public class NewtonRaphson {
    public NewtonRaphson(Funcao fn, DefaultListModel list) {
        this.fn = fn;
        this.list = list;
    }

    public double calcular(double x0, double eps) {
        double xn1;
        double xn;
        double fx;
        double dfx;
        xn = x0;
        list.addElement(String.format("x0 = %.14f, eps = %.14f", x0, eps));
        while (true) {
            fx = fn.f(xn);
            dfx = fn.df(xn);
            xn1 = xn - fx / dfx;
            list.addElement(String.format("xn = %.14f, xn1 = %.14f, fx = %.14f, dfx = %.14f, delta = %.14f", xn, xn1, fx, dfx,
                Math.abs(xn1 - xn)));
            if (Math.abs(xn1 - xn) < eps)
                break;
            xn = xn1;
        }
        list.addElement(String.format("Resultado: x = %.14f -> f(x) = %.14f", xn1, fx));
        return xn1;
    }

    private Funcao fn;
    private DefaultListModel list;
}
// ExemploNewtonRaphson.java
package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ExemploNewtonRaphson extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JScrollPane scpIteracoes = null;
    private JList lstIteracoes = null;
    private DefaultListModel modIteracoes = new DefaultListModel();
    private JPanel pnlEntrada = null;
    private JLabel lblEntrada = null;
    private JTextField txtEntrada = null;
    private JPanel pnlBotoes = null;
    private JButton btnCalcular = null;
    private JLabel lblCasasDecimais = null;
    private JTextField txtCasasDecimais = null;

    private JScrollPane getScpIteracoes() {
        if (scpIteracoes == null) {
            scpIteracoes = new JScrollPane();
            scpIteracoes.setViewportView(getLstIteracoes());
        }
        return scpIteracoes;
    }

    private JList getLstIteracoes() {
        if (lstIteracoes == null) {
            lstIteracoes = new JList();
            lstIteracoes.setModel(modIteracoes);
        }
        return lstIteracoes;
    }

    private JPanel getPnlEntrada() {
        if (pnlEntrada == null) {
            lblCasasDecimais = new JLabel();
            lblCasasDecimais.setText("Casas Decimais:");
            lblCasasDecimais.setHorizontalAlignment(SwingConstants.RIGHT);
            GridLayout gridLayout = new GridLayout();
            gridLayout.setRows(1);
            lblEntrada = new JLabel();
            lblEntrada.setText("Estimativa Inicial:");
            lblEntrada.setHorizontalAlignment(SwingConstants.RIGHT);
            pnlEntrada = new JPanel();
            pnlEntrada.setLayout(gridLayout);
            pnlEntrada.add(lblEntrada, null);
            pnlEntrada.add(getTxtEntrada(), null);
            pnlEntrada.add(lblCasasDecimais, null);
            pnlEntrada.add(getTxtCasasDecimais(), null);
        }
        return pnlEntrada;
    }

    private JTextField getTxtEntrada() {
        if (txtEntrada == null) {
            txtEntrada = new JTextField();
        }
        return txtEntrada;
    }

    private JPanel getPnlBotoes() {
        if (pnlBotoes == null) {
            pnlBotoes = new JPanel();
            pnlBotoes.setLayout(new FlowLayout());
            pnlBotoes.add(getBtnCalcular(), null);
        }
        return pnlBotoes;
    }

    private JButton getBtnCalcular() {
        if (btnCalcular == null) {
            btnCalcular = new JButton();
            btnCalcular.setText("Calcular!");
            btnCalcular.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    modIteracoes.clear();
                    NewtonRaphson nr = new NewtonRaphson(new Funcao() {
                        @Override
                        public double f(double x) {
                            return 4.0 * Math.pow(x, 5) - 7 * x * x + 2;
                        }
                        @Override
                        public double df(double x) {
                            return 20 * Math.pow(x, 4) - 14 * x;
                        }
                    }, modIteracoes);
                    nr.calcular(Double.parseDouble(txtEntrada.getText()), 
                        Math.pow(10, -Integer.parseInt (txtCasasDecimais.getText())));
                }
            });
        }
        return btnCalcular;
    }

    private JTextField getTxtCasasDecimais() {
        if (txtCasasDecimais == null) {
            txtCasasDecimais = new JTextField();
        }
        return txtCasasDecimais;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ExemploNewtonRaphson thisClass = new ExemploNewtonRaphson();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    public ExemploNewtonRaphson() {
        super();
        initialize();
    }

    private void initialize() {
        this.setSize(504, 221);
        this.setContentPane(getJContentPane());
        this.setTitle("Exemplo de Cálculo de Raízes via Newton-Raphson");
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getPnlEntrada(), BorderLayout.NORTH);
            jContentPane.add(getScpIteracoes(), BorderLayout.CENTER);
            jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }

}  //  @jve:decl-index=0:visual-constraint="10,10" 


Dica adicional:

Sempre que puder, utilize o tipo primitivo double ao invés da classe Double.

Muito obrigado =) pela dica ^^

esse exercício estou fazendo para mim mesmo, hehe mto mais fácil do que fazer na mão né =D

vlw

Se esse código tivesse sido postado semestre passado, teria me facilitado algumas coisas hahaha muito bom o código.

Estou fazendo esta disciplina de CN porém estamos implementando em MATLAB, mas Java é Java hehe =D

tenho algumas exemplos em Matlab aqui, mas estou fazendo em java só pra estudar para um prova básica aq! hehe

t+