java二分法求函数的零点
时间: 2023-12-20 07:31:38 浏览: 45
以下是Java中使用二分法求函数零点的示例代码:
```java
public class BinarySearch {
public static void main(String[] args) {
double left = 1.5; // 区间左端点
double right = 2.4; // 区间右端点
double mid = (left + right) / 2; // 区间中点
double eps = 1e-6; // 精度要求
while (Math.abs(f(mid)) > eps) { // 当中点函数值的绝对值大于精度要求时
if (f(mid) > 0) { // 如果中点函数值大于0,则根在左侧
right = mid; // 将右端点移动到中点
} else { // 如果中点函数值小于0,则根在右侧
left = mid; // 将左端点移动到中点
}
mid = (left + right) / 2; // 更新中点
}
System.out.println("函数零点为:" + mid); // 输出结果
}
// 定义函数f(x)
public static double f(double x) {
return x * x - 3 * x + 2;
}
}
```