Untitled

mail@pastecode.io avatar
unknown
java
a month ago
1.9 kB
1
Indexable
Never
import java.util.InputMismatchException;
import java.util.Scanner;

public class Fungsi1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        double lowerBound, upperBound, error, tolerance;
        int maxIterations;

        try {
            System.out.print("Masukkan batas bawah: ");
            lowerBound = scanner.nextDouble();

            System.out.print("Masukkan batas atas: ");
            upperBound = scanner.nextDouble();

            System.out.print("Masukkan toleransi error: ");
            tolerance = scanner.nextDouble();

            System.out.print("Masukkan jumlah iterasi maksimum: ");
            maxIterations = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Input tidak valid. Masukkan angka.");
            return;
        }

        double root = findRoot(lowerBound, upperBound, tolerance, maxIterations);

        if (root != Double.NaN) {
            System.out.printf("Akar persamaan x + exp(x) adalah: %.4f\n", root);
        } else {
            System.out.println("Tidak dapat menemukan akar dalam batas yang ditentukan.");
        }
    }

    private static double findRoot(double lowerBound, double upperBound, double tolerance, int maxIterations) {
        double root = Double.NaN;

        for (int i = 0; i < maxIterations; i++) {
            double mid = (lowerBound + upperBound) / 2.0;
            double fMid = mid + Math.exp(mid);

            if (Math.abs(fMid) < tolerance) {
                root = mid;
                break;
            } else if (fMid * (lowerBound + Math.exp(lowerBound)) > 0) {
                lowerBound = mid;
            } else {
                upperBound = mid;
            }
        }

        return root;
    }
}
Leave a Comment