如果R中的条件语句的长度大于1

时间:2015-07-27 04:45:26

标签: r

我在R中编写了黄金分割搜索的代码。在评估函数f1和f2时,我在f1和f2中只有一个元素。但在执行f1f2时,警告说:

  

if语句长度大于1。

我的代码:

golden.section.search1 = function(f, lower.bound, upper.bound, tolerance)
{

   golden.ratio = (sqrt(5)-1)/2

   ### Use the golden ratio to set the initial test points
   x1 = upper.bound - golden.ratio*(upper.bound - lower.bound)
   x2 = lower.bound + golden.ratio*(upper.bound - lower.bound)


   ### Evaluate the function at the test points
   f1 = (1/8)*colSums(f(x1))
   print(f1)
   f2 = (1/8)*colSums(f(x2))
   print(f2)

   iteration = 0

   while (abs(upper.bound - lower.bound) > tolerance)
   {
      iteration = iteration + 1

      cat('', '\n')
      cat('Iteration #', iteration, '\n')

      if (f1 < f2)

      {
         cat('f2 > f1', '\n')
         ### Set the new lower bound
         lower.bound = x2
     cat('New Upper Bound =', upper.bound, '\n')
         cat('New Lower Bound =', lower.bound, '\n')
         ### Set the new upper test point
         ### Use the special result of the golden ratio
         x2 = x1
         f2 = f1

         ### Set the new lower test point
         x1 = lower.bound + golden.ratio*(upper.bound - lower.bound)
    cat('New lower Test Point = ', x2, '\n')
         f1 = f(x1)
      } 
      else
      {

          cat('f2 < f1', '\n')

         ### Set the new upper bound
         upper.bound = x1
         cat('New Upper Bound =', upper.bound, '\n')
         cat('New Lower Bound =', lower.bound, '\n')

         ### Set the new upper test point
         x1 = x2
      cat('New Upper Test Point = ', x1, '\n')

         f1 = f2
         ### Set the new upper test point
         x2 = upper.bound - golden.ratio*(upper.bound - lower.bound)
     cat('New Lower Test Point = ', x2, '\n')
         f2 = f(x2)
      }



  }
   ### Use the mid-point of the final interval as the estimate of the optimzer


 minimizer = (lower.bound + upper.bound)/2
   cat('Estimated Minimizer =', minimizer, '\n')


}

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案。函数评估必须在while循环中完成,并且不会发生此错误。

相关问题