【问题标题】:How can I find x0 in Newton's method如何在牛顿法中找到 x0
【发布时间】: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


【解决方案1】:

牛顿公式是

x1 = x0 - (f(x0)/f'(x0))

当你插入你的函数时,你会得到以下代码片段:

double x1 = x0 - function(a, b, c, x0) / derivativeOfFunction(a, b, x0);

你可以把它包装在一个 for 循环中:

for (int i = 1; i <= n; i++) {
    double x1 = x0 - function(a, b, c, x0) / derivativeOfFunction(a, b, x0);
}

但这会计算 n 次 x1 的值,并且结果会在 for 循环终止后丢失。

所以你需要一个用x0初始化并修改n次的变量:

double xi = 0;
for (int i = 1; i <= n; i++) {
    xi = xi - function(a, b, c, xi) / derivativeOfFunction(a, b, xi);
}
System.out.println("xn="+xi);

那么 xn 的值就是 n 次迭代后 xi 的值。

请注意,您甚至可以将 for 循环的主体缩短为

double xi = 0;
for (int i = 1; i <= n; i++) {
    xi -= function(a, b, c, xi) / derivativeOfFunction(a, b, xi);
}
System.out.println("xn="+xi);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 2017-05-05
    • 1970-01-01
    • 2013-10-24
    • 2019-06-19
    • 2015-01-06
    • 2018-07-30
    相关资源
    最近更新 更多