我正在寻找一种将一个方法作为参数传递到另一个方法中的方法。
我目前正在尝试使用以下代码在 Java 中模拟牛顿法 ( http://en.wikipedia.org/wiki/Newton%27s_method ):
public class Newton {
// Iterationmethod
public void newtonCalc(double x0) {
double x;
// counter
int i = 0;
//Newton-Iteration for x0
x = x0 - (y2(x0) / y2Deriv(x0));
while (Math.sqrt(y2(x)*y2(x)) >= Math.pow(10, -10)){
//Newton-Iteration x(n+1)
x = x - (y2(x))/ y2Deriv(x);
i++;
System.out.printf("%d. %.11f\n",i,y2(x));
}
System.out.printf("%d steps were necessary for a resolution of 10^-10", i);
}
// Function for (2)
public static double y2(double x) {
return Math.sin(x) / (1 - Math.tan(x));
}
// Derivative for (2)
public static double y2Deriv(double x) {
return (Math.cos(x) + Math.sin(x) * Math.tan(x) * Math.tan(x))
/ ((Math.tan(x) - 1) * (Math.tan(x) - 1));
}
// Function for (4)
public static double y4(double x) {
return Math.exp(-1/Math.sqrt(x));
}
// Derivative for (4)
public static double y4Deriv(double x) {
return Math.exp(-1/Math.sqrt(x))/(2*Math.pow(x, 3d/2));
}
public static void main(String[] args) {
Newton newton = new Newton();
newton.newtonCalc(1);
}
}
newtonCalc(x0) 获取应该开始迭代的 x0。 但函数 (y2) 现在被硬编码到该方法中。我希望它是灵活的。 例如 newtonCalc(double x0, Method y) 从 x0 开始运行 y 的迭代。 我有 2 个不同的函数(y2 和 y4 都是来 self 的讲座练习表的函数,加上其在迭代方法中使用的导数 y2Deriv 和 y4Deriv)。
我知道传递方法是不可能的,但我没有得到任何简单的解决方法。
如果不清楚或者我错过了任何必要的信息,请原谅我!
问候,
Tak3r07
最佳答案
从 Java 8 开始,使用 lambda expressions 是完全可能的。
关于java - 将方法传递给方法的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24098902/