【发布时间】:2021-12-20 13:12:01
【问题描述】:
牛顿法
x1 = x0 - (f(x0)/f'(x0))
x2 = x1 - (f(x1)/f'(x1))
.
.
.
xn = xn-1 - (f(xn-1)/f'(xn-1))
这里 x0 显示初始根预测。 f'(x) 表示 f(x) 函数的导数。 程序将从用户那里获取值 a、b、c、n、x0。 该程序将找到 axx + b*x + c = 0 方程的根。 程序将打印 xn 值。
我将 a、b、c 和 x0 定义为双精度数据类型。我将 n 的值定义为 int 数据类型。如何定义与牛顿法相关的 for 循环或 while 循环?
这里我通过 Scanner 类从用户那里获取值:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("a = ");
double a = sc.nextDouble();
System.out.print("b = ");
double b = sc.nextDouble();
System.out.print("c = ");
double c = sc.nextDouble();
System.out.print("n = ");
int n = sc.nextInt();
System.out.print("x0 = ");
double x0 = sc.nextInt();
}
然后我将方法定义为函数和导数函数方法。在 main 方法中如何调用函数或者我需要在 main 方法中创建 for 或 while 循环?我该怎么办?
public static double function(double a, double b, double c, double x) {
return (a * Math.pow(x, 2)) + (b * x) + c;
}
public static double derivativeOfFunction(double a, double b, double x) {
return 2 * a * x + b;
}
【问题讨论】:
-
x0 是在原始根可能附近的随机猜测。
-
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("a = ");双一 = sc.nextDouble(); System.out.print("b = ");双 b = sc.nextDouble(); System.out.print("c = ");双 c = sc.nextDouble(); System.out.print("n = "); int n = sc.nextInt(); System.out.print("x0 = ");双 x0 = sc.nextInt();在这里,我通过 Scanner 类从用户那里获取值
-
然后我将方法定义为函数和导数方法。在 main 方法中如何调用函数或者我需要在 main 方法中创建 for 或 while 循环?我能做些什么 ? public static double function(double a, double b, double c, double x) { return (a * Math.pow(x, 2)) + (b * x) + c; } 公共静态双导数函数(双a,双b,双x){返回2 * a * x + b; }
-
您可以尝试使用fast inverse square root 快速猜测。警告邪恶的浮点位级黑客攻击。
-
您的任务很好地映射到一个 for 循环:
for (int i = 1; i <= n; i++) {...}。调用函数同样简单:double result = function(a, b, c, x0);和double d = derivativeOfFunction(a, b, x0);
标签: java for-loop while-loop java.util.scanner do-while