-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBisection.java
More file actions
50 lines (40 loc) · 1.46 KB
/
Copy pathBisection.java
File metadata and controls
50 lines (40 loc) · 1.46 KB
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
46
47
48
49
50
import java.util.Scanner;
public class BiSection {
public static double f(double x) {
return x * x - 4;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("(a) değerini giriniz: ");
double a = scanner.nextDouble();
System.out.println("(b) değerini giriniz: ");
double b = scanner.nextDouble();
// iterasyon epsilon değerinden küçük olmamalı
System.out.println("Enter tolerance (ε): ");
double tol = scanner.nextDouble();
System.out.println("Enter maximum iterations: ");
int maxIterations = scanner.nextInt();
if (f(a) * f(b) >= 0) {
System.out.println("Invalid interval: f(a) and f(b) must have opposite signs.");
return;
}
double root = bisectionMethod(a, b, tol, maxIterations);
System.out.println("Approximated root: " + root);
}
public static double bisectionMethod(double a, double b, double tol, int maxIterations) {
double c = a; // Midpoint
for (int i = 0; i < maxIterations; i++) {
c = (a + b) / 2;
if (Math.abs(f(c)) < tol || (b - a) / 2 < tol) {
break;
}
// (right bracket with middle) or (left bracket with middle)
if (f(a) * f(c) < 0) {
b = c;
} else {
a = c;
}
}
return c;
}
}