计算机器人在Java中移动的距离

-3 java math function

我正在为学校做一个项目,要求我搬一个机器人.机器人每秒移动的距离(变量t)由下面的函数计算.

数学函数

第一个功能很简单.第二个和第三个是我被卡住的地方.我怎么写F(t-1)?以下是我到目前为止的情况.

if (t == 0) {
    distance = 2;
} else if (t > 0 && <=6 || t > 12) {
    // No clue on how to write the 2nd distance equation.
} else if (t >= 7 && <=12) {
    // No clue on how to write the 3rd distance equation.
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

递归确实不是解决这个问题的必要条件.

请注意,在每个非零时间情况下,F(t) = F(t-1) + something.

所以你可以简单地做:

double f = 2;  /* Initial value at t=0 */
for (int t = 1; t <= maxT; ++t) {  // maxT is the maximum value of t.
  if (t <= 6 || t > 12) {
    f += /* something for case 2 */;
  } else {
    f += /* something for case 3 */;
  }
}
System.out.println(f);
Run Code Online (Sandbox Code Playgroud)

可以用递归做到这一点,但你会得到一个StackOverflowErrorif maxT变得适度大; 相反,使用循环将适用于任意大maxT(模数浮点错误).


正如@Andreas指出的那样,你可以在不循环遍历所有值的情况下执行此操作t:

double f = 2 * (maxT + 1);
for (int t = 7; t <= maxT && t <= 12; ++t) {
  f += log(t) - 2;
}
Run Code Online (Sandbox Code Playgroud)

并且您可以通过预先计算值来消除该循环.

  • 对于t = 1..6:`F(t)= t*2`.对于t> 12:`F(t)= F(12)+(t-12)*2`.对于t = 7..12,你可以做循环,或6个预先计算的常量数组来计算`12 + log(7)+ log(8)+ log(9)+ log(10)+ log(11)+ log(12)`或取决于`t`的任何子集. (2认同)