我有这段在网上找到的 Python 代码,想知道如何将它翻译成 Java。我的问题不是算法,而是如何处理函数的参数。
代码如下:
def ternarySearch(f, left, right, absolutePrecision):
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if f(leftThird) < f(rightThird):
return ternarySearch(f, leftThird, right, absolutePrecision)
return ternarySearch(f, left, rightThird, absolutePrecision)
我想知道函数定义是什么样的。例如,返回 y=x^2+3
的函数看起来像:
public static int y(int x){
return x*x+3;
}
但是
return ternarySearch(f, leftThird, right, absolutePrecision)
对我不起作用,我想知道该怎么做。
更新:
所以例如我有 y=3*x+2 它会像这样吗?
interface MyFunctor {
int myFunction(int x);
}
class MyFunctorImpl implements MyFunctor {
int myFunction(int x) {
return 3*x+2
}
}
像这样吗?
最佳答案
在 Java 中,没有高阶函数。也就是说,您不能将一个函数作为参数传递给另一个函数。您可以做的是使用命令模式;定义一个支持所需方法的接口(interface),然后传递实现该方法的接口(interface)实例。
例如:
int ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if (f.myFunction(leftThird) < f.myFunction(rightThird)) {
return ternarySearch(f, leftThird, right, absolutePrecision)
}
return ternarySearch(f, left, rightThird, absolutePrecision)
}
和
interface MyFunctor {
int myFunction(int arg);
}
和
class MyFunctorImpl implements MyFunctor {
int myFunction(int arg) {
// implementation
}
}
然后您可以使用 MyFunctorImpl
的实例作为第一个参数来调用 ternarySearch
。
关于java - 我如何在 Java 中实现这个 Python 片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874487/