【发布时间】:2014-07-28 17:33:28
【问题描述】:
我正在寻找一种将方法作为参数传递给另一个方法的方法。
我目前正在尝试使用以下代码在 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,它们都是我讲座中的练习表中的函数,加上迭代方法中使用的派生词 y2Deriv 和 y4Deriv)。
我知道传递方法是不可能的,但我没有任何简单的解决方法。
如果不清楚或者我错过了任何必要的信息,请原谅我!
问候,
Tak3r07
【问题讨论】:
标签: java function math methods parameters