2016-08-17 35 views
-3

我正在爲一所需要我移動機器人的學校開展項目。機器人每秒移動的距離(變量t)由下面的函數計算。計算機器人在Java中的移動距離

Math Function

第一個功能是方便。另一個是第二個和第三個是卡住的地方。我會如何寫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. 
} 
+1

你如何使用這個功能呢?也許如果你解釋上下文或者給出你正在嘗試的函數定義可能會更好一些。 –

+0

你將不得不使用遞歸來解決這個問題!你知道如何使用遞歸嗎? –

+0

@RenukaDeshmukh不,你不知道。 –

回答

2

這是一個涉及使用recursion的問題。大體上,請密切注意F t-1,因爲這是指在t-1處對特定功能的評估。

我不會寫了所有的代碼,但我給你的一些基本知識:

  • 當t = 0,回報2。這是你的基本情況。
  • 當t是包容或大於12 0至6,在t-1返回功能的評價,並添加2
  • 當t是7和12之間包括兩端,返回的評價在t-1處的函數,並且添加日誌(t)。

這裏有些東西可以讓你至少開始正確的方向。

public double evaluateDistance(int t) { 
    if(t == 0) { 
     return 2; 
    } else if(t > 0 && t <= 6) || (t > 12) { 
     // Think about this - it would involve another call to evaluateDistance, but what is t again? 
    } else if(t >= 7 && t <= 12) { 
     // Another evaluation involving the function. 
     // For free, the change of base operation you'll need to get base-2 evaluation for the log: 
     return ??? + Math.log(t)/Math.log(2); 
    } 
} 
+0

我會認爲這項任務書寫得不好。如果函數被定義爲** F(t)**,而不是** F t **,則** F t-1 **是錯誤的,因爲它應該是** F(t-1 )**。無論如何,因爲只有一個遞歸存在,並且對於't-1',總是循環比遞歸更好,但首先解釋遞歸解決方案是好的。 *(似乎在評論中不起作用,但你知道我的意思)* – Andreas

+0

我不贊同@Andreas的概念。一個循環可能會更有效率和更直接,但看到這兩種方式不會受到傷害。 – Makoto

+0

這是我的觀點。 *雙向*。你只是展示了遞歸方式,這是賦予賦值最直接的方式,我已經鼓掌稱呼了,但是你沒有顯示循環的「更好」方式,這不會導致'StackOverflowException'出現大的值't'。 – Andreas

5

Recursion確實沒有必要解決這個問題。

請注意,在每個非零時間情況下,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); 

可以遞歸做到這一點,但你會得到一個StackOverflowError如果maxT變得謙虛地大;相反,使用循環將適用於任意大的模數浮點錯誤(模浮點錯誤)。


正如@Andreas指出的那樣,你可以做到這一點沒有遍歷的t所有值:

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

,您可以通過預先計算的值,消除環路了。

+0

你知道你可以不循環,對吧? – Andreas

+0

@Andreas你的意思是遞歸或其他方式? –

+2

對於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'的任何子集。 – Andreas

0

想想我想通了。對不起,如果我不清楚我需要什麼,只需要弄清楚如何編寫函數中的方程。想想我想通了。

public double move() 
{ 
    int t = 0; 
    if(t == 0) // After the first second, robot moves 2 
    { 
     distance = 2; 
    } 
    else if(t > 0 && t <= 6 || t > 12) // From seconds 0 to 6 and after 12, robot moves distance equation 
    { 
     distance = (2*t)+2; 
    } 
    else if(t >= 7 && t <= 12) // From seconds 7 to 12, robot moves distances equation 
    { 
     distance = (2*t)+(Math.log(t)/Math.log(2)); 
    } 
    position = position + distance; 
    return position; 
} 

}