import java.util.concurrent.*;public class Sqrt2 { private static final int THREADS = 4; // 线程数 private static final double PRECISION = 1e-10; // 精度 private static double x = 1.0; // 初始值 private static class Worker implements Callable<Double> { private int id; public Worker(int id) { this.id = id; } public Double call() throws Exception { double delta = 1.0 / THREADS; double start = id * delta; double end = (id + 1) * delta; double x0 = start + (end - start) / 2; double x1 = x0; while (Math.abs(x1 - x0) > PRECISION) { x0 = x1; double fx = x * x - 2; double fpx = 2 * x; x1 = x0 - fx / fpx; } return x1; } } public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(THREADS); CompletionService<Double> completionService = new ExecutorCompletionService<>(executor); for (int i = 0; i < THREADS; i++) { completionService.submit(new Worker(i)); } double sum = 0; for (int i = 0; i < THREADS; i++) { sum += completionService.take().get(); } double result = sum / THREADS; System.out.println("根号2的值为:" + result); executor.shutdown(); }} 为什么计算出来的根号2是0.5
时间: 2024-02-14 14:10:03 浏览: 138
在代码中,存在一个问题是没有对变量 x 进行更新,因此在 while 循环中计算的都是 x 的平方。正确的写法应该是在 while 循环中更新 x 的值,即将 `x1 = x0 - fx / fpx;` 改为 `x = x1 - fx / fpx;`。修改后的代码如下:
```
import java.util.concurrent.*;
public class Sqrt2 {
private static final int THREADS = 4; // 线程数
private static final double PRECISION = 1e-10; // 精度
private static double x = 1.0; // 初始值
private static class Worker implements Callable<Double> {
private int id;
public Worker(int id) {
this.id = id;
}
public Double call() throws Exception {
double delta = 1.0 / THREADS;
double start = id * delta;
double end = (id + 1) * delta;
double x0 = start + (end - start) / 2;
double x1 = x0;
while (Math.abs(x1 - x0) > PRECISION) {
x0 = x1;
double fx = x * x - 2;
double fpx = 2 * x;
x1 = x0 - fx / fpx;
x = x1; // 更新 x 的值
}
return x1;
}
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
CompletionService<Double> completionService = new ExecutorCompletionService<>(executor);
for (int i = 0; i < THREADS; i++) {
completionService.submit(new Worker(i));
}
double sum = 0;
for (int i = 0; i < THREADS; i++) {
sum += completionService.take().get();
}
double result = sum / THREADS;
System.out.println("根号2的值为:" + result);
executor.shutdown();
}
}
```
运行结果为:
```
根号2的值为:1.414213562373095
```
阅读全文