如何在Java中实现此Python代码段?

dat*_*ili 1 python java function

我有这个在线发现的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)
Run Code Online (Sandbox Code Playgroud)

我想知道函数定义是什么样的.例如,返回的函数y=x^2+3如下所示:

public static int y(int x){
 return x*x+3;
}
Run Code Online (Sandbox Code Playgroud)

 return ternarySearch(f, leftThird, right, absolutePrecision)
Run Code Online (Sandbox Code Playgroud)

不适合我,我想知道该怎么做.

更新:

所以例如我有y = 3*x + 2它会是这样的吗?

interface MyFunctor {
 int myFunction(int x);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int  x) {
      return 3*x+2
  }
}
Run Code Online (Sandbox Code Playgroud)

像这样?

dan*_*ben 8

在Java中,没有高阶函数.也就是说,您不能将函数作为参数传递给另一个函数.你可以做的是使用命令模式; 定义支持所需方法的接口,然后传递实现该方法的接口实例.

例如:

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)
}
Run Code Online (Sandbox Code Playgroud)

interface MyFunctor {
  int myFunction(int arg);
}
Run Code Online (Sandbox Code Playgroud)

class MyFunctorImpl implements MyFunctor {
  int myFunction(int arg) {
     // implementation
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以调用ternarySearch一个实例MyFunctorImpl作为第一个参数.