• Lenguaje

    Java

  • Descripción

    Encuentra la solución de f(x) = f(x)=x³+2x²+10x-20 con el método de la secante

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class Secante {

    public static final int ITERACIONES_MAXIMAS = 100;
    public static final double TOLERANCIA = 0;

    public static double f (double x) {
        return x*x*x + 2.0*x*x + 10.0*x - 20;
    }

    public static void main (String[] args) throws UnsupportedEncodingException {
        Scanner in = new Scanner(System.in);
        double x0, x1, temp, err;
        int n = 1;
        PrintStream out = System.getProperties().get("os.name").equals("Linux") || System.console()==null ?
            System.out : new PrintStream(System.out, true, "CP850");
        out.println("M\u00E9todo de la Secante para el c\u00E1lculo de la funci\u00F3n: f(x)=x\u00B3+2x\u00B2+10x-20");
        out.print("\nIngrese la aproximaci\u00F3n inicial x0: ");
        x0 = in.nextDouble();
        out.print("Ingrese la aproximaci\u00F3n inicial x1: ");
        x1 = in.nextDouble();
        out.printf("\n%-20s%-20s%-20s\n", "n", "Xn", "Error");
        out.println("0                   " + x0);
        do {
            err = Math.abs(x0-x1);
            out.printf("%-20d%-20g%-20g\n", n, x1, err);
            if(err!=0) {
                temp = x1;
                x1 = x1 - (x1 - x0) * f(x1) / (f(x1) - f(x0));
                x0 = temp;
            }
            n++;
        } while(err>TOLERANCIA && n<=ITERACIONES_MAXIMAS);
        out.println();
        if(n<ITERACIONES_MAXIMAS)
            out.println("La soluci\u00F3n es: " + x1);
        else
            out.println("No se encontr\u00F3 la ra\u00EDz: cambiar aproximaciones iniciales o aumentar ITERACIONES_MAXIMAS");
        out.println();
    }
}