Código de Calculo Numérico

APROXIMAÇÕES DE INTEGRAIS:

package calculonumerico;

import java.util.Scanner;

public class AproximacaoDeIntegrais {
    static double[] valXSimpsom, valXTrapezio;
    static double xa, xb, x1, hS, hT;
    static int nS = 10, nT = 10;
    static Scanner input = new Scanner(System.in);
    
    private static double funcao(double x) {
        return Math.sin(x);
    }
    private static double funcaoII(double x) {
        return -Math.sin(x);
    }
    private static double funcaoIV(double x) {
        return Math.sin(x);
    }
    private static double funcaoF(double x) {
        return -Math.cos(x);
    }
    private static double integralResolvida() {
        return (funcaoF(xb) - funcaoF(xa));
    }
    
    public static void main(String[] args) {
        System.out.println("Insira o valor de a: ");
        xa = input.nextDouble();
        System.out.println("\nInsira o valor de b: ");
        xb = input.nextDouble();
        
        double resultadoS = regraDoSimpson();
        System.out.println("\nRegra Simpsom : " + resultadoS);
        double erroS = erroDeTruncamentoDoSimpson();
        System.out.println("Erro de truncamento do Simpson: " + erroS);
        System.out.println("Desvio Absoluto: " + desvioAbsoluto(resultadoS));
        System.out.println("Desvio Relativo Por Centual : " + desvioRelativoPorCentual(resultadoS));
        
        double resultadoT = regraDoTrapezio();
        System.out.println("\nRegra do Trapezio : " + resultadoT);
        double erroT = erroDeTruncamentoDoTrapezio();
        System.out.println("Erro de truncamento do Trapezio: " + erroT);
        System.out.println("Desvio Absoluto: " + desvioAbsoluto(resultadoT));
        System.out.println("Desvio Relativo Por Centual : " + desvioRelativoPorCentual(resultadoT));
        
        comparar(erroS,erroT,"Simpson","Trapezio");
        
    }
    
    private static void calcularHSimpsons() {
        x1 = (xb + xa)/2;
        hS = x1 - xa;
    }
    private static void iniciarValsXSimpsom() {
        valXSimpsom = new double[nS];
        for(int i = 1; i < nS; i++) {
            valXSimpsom[i-1] = xa + i*hS;
        }
    }
    private static double partesImpares() {
        double valy = 0;
        if(nS > 2) {
            for(int i = 0; i < nS && i%2 == 0; i++) {
                valy += funcao(valXSimpsom[i]);
            }
        } else if(nS == 2){
            valy = funcao(x1);
        }
        return valy;
    }
    private static double partesPares() {
        double valy = 0;
        if(nS > 2) {
            for(int i = 0; i < nS && i%2 != 0; i++) {
                valy += funcao(valXSimpsom[i]);
            }
        }
        return valy;
    }
    private static double regraDoSimpson() {
        calcularHSimpsons();
        if(hS > 1) {
            iniciarValsXSimpsom();
        } else {
            nS = 2;
        }
        double y = hS*(funcao(xa) + 4*partesImpares() + 2*partesPares() + funcao(xb))/3;
        return y;
    }
    private static double erroDeTruncamentoDoSimpson() {
        return nS*Math.pow(hS,5)*(Math.min(Math.abs(funcaoIV(xa)), Math.abs(funcaoIV(xb))))/180;
    }
    
    private static void calcularHTrapezio() {
        hT = (xb - xa)/nT;
    }
    private static void iniciarValsXTrapezio() {
        valXTrapezio = new double[nT];
        for(int i = 1; i < nT; i++) {
            valXTrapezio[i-1] = xa + i*hT;
        }
    }
    private static double valDasPartes() {
        double valy = 0;
        if(nT > 1) {
            for(int i = 0; i < nT; i++) {
                valy += funcao(valXTrapezio[i]);
            }
        }
        return valy;
    }
    private static double regraDoTrapezio() {
        calcularHTrapezio();
        if(hT > 1) {
            iniciarValsXTrapezio();
        } else {
            nT = 1;
        }
        return hT*(funcao(xa) + 2*valDasPartes() + funcao(xb))/2;
    }
    private static double erroDeTruncamentoDoTrapezio() {
        return Math.pow(hT, 3)*(Math.min(Math.abs(funcaoII(xa)),Math.abs(funcaoII(xb))))/12;
    }
    
    private static double desvioAbsoluto(double resultado) {
        return Math.abs(integralResolvida() - resultado);
    }
    private static double desvioRelativoPorCentual(double resultado) {
        return Math.abs((integralResolvida() - resultado)/integralResolvida());
    }
    private static void comparar(double erro1, double erro2, String metodo1, String metodo2) {
        String metodo = "";
        if(erro1 > erro2) {
            metodo = metodo2;
        } else {
            metodo = metodo1;
        }
        System.out.println("O melhor metodo foi do " + metodo + ", pois o seu erro de truncamento foi menor.");
    }
}

SISTEMAS DE EQUAÇÕES LINEARES ALGEBRICAS

package calculonumerico;

import java.util.Scanner;

public class SistemaDeEquacoesLinearesAlgebricas {
    static double[][] matriz;
    static double[] vetorXEG, vetorB, vetorXGJ, da, vetorChute;
    static int n;
    static double tolerancia = 0.01, dr;
    static Scanner input = new Scanner(System.in);
    
    private static void corrigirValor(double[] linha) {
        String lin = "";
        for(int j = 0; j < n; j++) {
            lin += "[" + linha[j] + "]"; 
        }
        System.out.println(lin);
        System.out.println("\nGostaria de mudar algum valor?");
        String resposta = input.next().toLowerCase();
        do{
            if(resposta.equals("sim")) {
                System.out.println("\nQual deles? (1 á " + n + ")");
                resposta = input.next();
                System.out.println("\nPor qual valor?");
                linha[Integer.parseInt(resposta)- 1] = input.nextDouble();
                System.out.println("\nCorrigir mais algum valor?");
                resposta = input.next().toLowerCase();
            }
        } while(resposta.equals("sim"));
    }
    
    private static double[] gerarLinha(int i) {
        System.out.println("\nPor favor, insira os elementos da linha " + (i + 1) + ", separados por ';' : ");
        String txt = input.next();
        double[] linha = new double[n];
        for(int j = 0; j < n; j++) {
            if(txt.contains(",")) {
                txt = txt.replaceAll(",", ".");
            }
            int indexDeParada = txt.indexOf(";");
            if(indexDeParada >= 0) {
                linha[j] = Double.parseDouble(txt.substring(0, indexDeParada));
            } else if(txt.length() > 0) {
                linha[j] = Double.parseDouble(txt);
            }
            txt = txt.substring(indexDeParada + 1);
        }
        corrigirValor(linha);
        return linha;
    }
    private static void gerarMatriz() {
        matriz = new double[n][n];
        for(int i = 0; i < n; i++) {
            matriz[i] = gerarLinha(i);
        }
    }
    
    private static void gerarVetorB() {
        vetorB = new double[n];
        System.out.println("\nQuais os valores do vetorB?");
        String txt = input.next();
        for(int j = 0; j < n; j++) {
            if(txt.contains(",")) {
                txt = txt.replaceAll(",", ".");
            }
            int indexDeParada = txt.indexOf(";");
            if(indexDeParada >= 0) {
                vetorB[j] = Double.parseDouble(txt.substring(0, indexDeParada));
            } else if(txt.length() > 0) {
                vetorB[j] = Double.parseDouble(txt);
            }
            txt = txt.substring(indexDeParada + 1);
        }
        corrigirValor(vetorB);
    }
    
    private static double[][] escalonamento() {
        double[][] matrizEscalonada = matriz;
        for(int i = 0; i < n; i++) {
            if(matrizEscalonada[i][i] == 0) {
                for(int linha = i+1; linha < n; linha++) {
                    if(matrizEscalonada[linha][i] != 0) {
                        double[] vetorAuxiliar = matrizEscalonada[i];
                        double elementoAuxiliar = vetorB[i];
                        
                        matrizEscalonada[i] = matrizEscalonada[linha];
                        vetorB[i] = vetorB[linha];
                        
                        matrizEscalonada[linha] = vetorAuxiliar;
                        vetorB[linha] = elementoAuxiliar;
                        break;
                    }
                }
            }
            double valorLideranca = matrizEscalonada[i][i];
            for(int j = 0; j < n; j++) {
                if(matrizEscalonada[i][j] != 0) {
                    matrizEscalonada[i][j] = matrizEscalonada[i][j]/valorLideranca;
                }
                if(vetorB[i] != 0) {
                    vetorB[i] = vetorB[i]/valorLideranca;
                }
            }
            for(int linha = i + 1; linha < n; linha++) {
                valorLideranca = matrizEscalonada[linha][i];
                for(int coluna = 0; coluna < n; coluna++) {
                    if(matrizEscalonada[i][coluna] != 0) {
                        matrizEscalonada[linha][coluna] -= valorLideranca*matrizEscalonada[i][coluna];
                    }
                }
                vetorB[linha] -= valorLideranca*vetorB[i];
            }
        }
        return matrizEscalonada;
    }
    private static void eliminacaoDeGauss() {
        double[][] matrizEscalonada = escalonamento();
        vetorXEG = new double[n];
        for(int i = n - 1; i >= 0; i--) {
            double somatorio = 0;
            for(int j = n - 1; j >= 0; j--) {
                if(i != j) {
                    somatorio += matrizEscalonada[i][j];
                }
            }
            double valorA = vetorB[i];
            double valorB = matrizEscalonada[i][i];
            vetorXEG[i] = (valorA - somatorio)/valorB;
        }
        exibirVetorSolucao(vetorXEG, "Metodo por Eliminação de Gauss");
    }
    
    private static void desvioAbsoluto() {
        da = new double[n];
        for(int i = 0; i < n; i ++) {
            da[i] = Math.abs(vetorXGJ[i] - vetorChute[i]);
        }
    }
    private static void desvioRelativo() {
        double daMax = da[0];
        double xMax = vetorXGJ[0];
        for(int i = 1; i < n; i++) {
            daMax = Math.max(daMax, da[i]);
            xMax = Math.max(Math.abs(xMax), Math.abs(vetorXGJ[i]));
        } 
        dr = daMax/xMax;
    }
    private static void metodoGaussJacob() {
        double[] alfa = new double[n];
        vetorXGJ = new double[n];
        vetorChute = new double[n];
        double alfaMax;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                alfa[i] += Math.abs(matriz[i][j]);
            }
            alfa[i] = alfa[i]/Math.abs(matriz[i][i]);
        }
        alfaMax = alfa[0];
        for(int i = 1; i < n; i++) {
            alfaMax = Math.max(alfaMax, alfa[i]);
        }
        if(alfaMax < 1) {
            double daMax, xMax;
            da = new double[n];
            do {
                for(int i = 0; i < n; i ++) {
                    double somatorio = 0;
                    for(int j = 0; j < n; j++) {
                        if(i != j) {
                            somatorio += matriz[i][j]*vetorChute[j];
                        }
                    }
                    vetorXGJ[i] = (vetorB[i] - somatorio)/matriz[i][i];
                }
                desvioAbsoluto();
                desvioRelativo();
                if(dr > tolerancia) {
                    vetorChute = vetorXGJ;
                }
            } while(dr > tolerancia);
            exibirVetorSolucao(vetorXGJ, "Metodo de Gauss-Jacob");
        } else {
            System.out.println("O alfa foi maior que 1, alfa = " + alfaMax);
            System.out.println("O metodo Gauss-Jacob não gera uma sequencia vetores X \nconvergentes do sistema independente da escolha da estimativa inicial.");
        }
    }
    
    public static void main(String[] args) {
        System.out.println("\nQual o tamanho da Matriz?");
        n = input.nextInt();
        gerarMatriz();
        gerarVetorB();
        eliminacaoDeGauss();
        metodoGaussJacob();
    }
    private static void exibirVetorSolucao(double[] vetor, String metodo) {
        String txt = "";
        for(int i = 0; i < n; i++) {
            txt += "[" + vetor[i] + "]";
        }
        txt += "\n";
        System.out.println(metodo + ": " + txt);
    }
}

BISSECAO:

package aproximacaoderaizes;

import static java.lang.Math.cos;
import static java.lang.Math.log;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import java.util.Scanner;

public class AproximacaoDeRaizes {
    static double xA, xB, tolerancia, nDeIteracoes;
    static double[] resultadoBissecao = new double[3];
    static double[] resultadoNewton = new double[3];
    static Scanner input = new Scanner(System.in);
    
    private static double funcao(double x) {
        //retorna o resultado da função com o valor x inserido
        double y = pow(x,2)/4 - cos(x);
        return y;
    }
    private static double funcaoI(double x) {
        //retorna o resultado da derivada da função com o valor x inserido
        return x/2 + sin(x);
    }
    public static void main(String[] args) {
        //inicia o código
        //caso em a = 1 e b = 1.5
        //caso em a = 1.1 e b = 1.3
        definirIntervalo();
        System.out.println("Numero de Iterações minimas: " + nDeIteracoes);
        System.out.println("f(a) = " + funcao(xA));
        System.out.println("f(b) = " + funcao(xB));
        System.out.println("-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-");
        metodoDaBissecao();
        metodoNewtonRaphson();
        System.out.println("_______________Resultados_________________");
        System.out.println("Método da Bisseção");
        resultadoFinal((int)resultadoBissecao[0], resultadoBissecao[1], resultadoBissecao[2]);
        System.out.println("__________________________________________");
        System.out.println("Método Newton-Raphson");
        resultadoFinal((int)resultadoNewton[0], resultadoNewton[1], resultadoNewton[2]);
    }
    private static void definirIntervalo() {
        //Define um intervalo (A,B)
        System.out.println("Defina um valor A: ");
        xA = input.nextDouble();
        System.out.println("Defina um valor B: ");
        xB = input.nextDouble();
        if (condicaoDasEstimativas(funcao(xA), funcao(xB))) {
            tolerancia = pow(10,-5);
            nDeIteracoes = (int)(log((xB - xA)/tolerancia)/log(2) + 1);
        } else {
            erroDeValores(funcao(xA), funcao(xB));
            definirIntervalo();
        }
    }
    
    private static void metodoDaBissecao() {
        //Aplica o método da Bissecao e guarda o numero de iterações feitas, o x encontrado e o valor da f(x);
        double x, xUm, xDois;
        int iteracao = 0;
        xUm = xA;
        xDois = xB;
        System.out.println("Começo da Bissecao:_____");
        do {
            System.out.println("@Entrada----------------------");
            System.out.println("x1 = " + xUm);
            System.out.println("x2 = " + xDois);
            iteracao++;
            x = estimativaX(xUm, xDois);
            if(funcao(x) > 0) {
                if(funcao(xUm) < 0) {
                    xDois = xUm;
                }
            } else {
                if(funcao(xUm) > 0) {
                    xDois = xUm;
                }
            }
            xUm = x;

            valoresDaIteracao(x, iteracao, funcao(x));
        } while(criterioDeParada(funcao(xUm)));
        resultadoBissecao[0] = iteracao;
        resultadoBissecao[1] = x;
        resultadoBissecao[2] = funcao(x);
    }
    private static void metodoNewtonRaphson() {
        //Aplica o método de Newton-Raphson e guarda o numero de iterações, o x encontrado e o valor de f(x);
        double xM, xUm, xDois;
        int iteracao = 0;
        xUm = xA;
        xDois = xB;
        System.out.println("Começo de Newton-Raphson:_____");
        do {
            System.out.println("@Entrada----------------------");
            System.out.println("x1 = " + xUm);
            System.out.println("x2 = " + xDois);

            if(iteracao > 0) {
                xUm = xDois;
            } else if(iteracao == 0) {
                xUm = estimativaX(xUm, xDois);
            }
            iteracao++;
            xDois = estimativaX(xUm);

            valoresDaIteracao(xDois, iteracao, funcao(xDois));

        } while(criterioDeParada(funcao(xDois)));
        resultadoNewton[0] = iteracao;
        resultadoNewton[1] = xDois;
        resultadoNewton[2] = funcao(xDois);
    }
    private static boolean condicaoDasEstimativas(double yUm, double yDois) {
        //Retorna true se a raiz estiver entre os dois y;
        return yUm*yDois < 0;
    }
    private static double estimativaX(double a, double b) {
        //Realiza a estimativa de x
        return (a+b)/2;
    }
    private static double estimativaX(double xM) {
        //Realiza a estimativa de x para o método de Newton-Raphson;
        return xM - funcao(xM)/funcaoI(xM);
    }
    private static boolean criterioDeParada(double y) {
        //Verifica se o y encontrado é menor que a tolerancia;
        if(y < 0) {
            y = y*(-1);
        }
        return y >= tolerancia;
    }
    private static void valoresDaIteracao(double x, int iteracoes, double y) {
        //Imprime a iteração atual e seus valores de x e f(x);
        System.out.println("@Saída------------------------");
        System.out.println("x = " + x);
        System.out.println("iteração = " + iteracoes);
        System.out.println("f(x) = " + y);
    }
    private static void erroDeValores(double yUm, double yDois) {
        //Alerta se entre os pontos a e b não se tem certeza de existir uma raiz;
        System.out.println("f(a) = " + yUm);
        System.out.println("f(b) = " + yDois);
        System.out.println("Mude o A ou o B!");
    }
    private static void resultadoFinal(int iteracoes, double x, double y) {
        //imprime o valor aproximado da raiz e o valor da f(x);
        System.out.println("Estimativa x" + iteracoes + " = " + x);
        System.out.println("f(x"+ iteracoes+") = " + y);
    }
}