2016-11-10 38 views
1

就像它在標題中說的那樣我有問題需要我自己製作電源和日誌方法,並在我的輸入中使用它們。 我的電源功能似乎很好,直到我嘗試在我的loga(b)函數中使用它。 一個問題是,我不明白我的日誌方法中的for循環,因爲我在課堂上覆制了一個循環以便稍後理解它。另一個問題是,我不知道Math.pow()是如何工作的,如果我有代碼或僞代碼,我可以猜測我自己的功能函數是如何不同的。 預先感謝,請在我身上輕鬆我對這一切還是比較陌生的。在日誌功能中使用遞歸功能,沒有Math.functions

import java.util.Scanner; 

public class Numbers { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     double i1; 
     double i2; 
     System.out.print("type your a:"); 
     i1 = input.nextDouble(); 
     System.out.print("type your b:"); 
     i2 = input.nextDouble(); 
     input.close(); 
     sumRange(i1, i2); 
     power(i1, i2); 
     log(i1, i2); 
     System.out.println("Sum from a to b: " + sumRange(i1, i2) + "\nFibonacci for A: " + fibonacci(i1) 
       + "\nFibonacci for B: " + fibonacci(i2) + "\nA^B:" + power(i1, i2) + "\na%b: " + mod(i1, i2) 
       + "\nloga (b)" + log(i1, i2)); 
    } 

    // if I'm honest I don't understand how the log code works exactly, 
    // what I do know is that this code calculates the correct log 
    // with Math.pow() function 
    // My own power function doesn't seem to work and I don't know how the 
    // MAth.pow() 
    // function is different from mine 
    static double log(double i1, double i2) { 
     double value = 0; 
     for (double i = 1; i > .001; i /= 10) { 
      while (!(power(i1, value) > i2)) { 
       value += i; 
      } 
      value -= i; 
     } 
     return value; 
    } 

    static double power(double i1, double i2) { 
     if (i2 == 0) { 
      return 1; 
     } 
     if (i2 == 1) { 
      return i1; 
     } 
     // The line below seems to cause problems since used in log(double, 
     // double) method 
     return i1 * power(i1, i2 - 1); 
    } 
    // I excluded my 3 other methods as they work fine and don't depend on 
    // each other to work 
+1

在比較和算術運算中混合使用雙精度和整數字面值是一個糟糕的主意。 – pjs

回答

-1

您的電源方法只適用於整數i2,否則遞歸永遠不會終止。

對於非整數i2您可以在縮小後至少在01之間進行一些線性插值。這對大基礎值i1來說是一個不好的近似值,但總比沒有好。

if(0<=i2 and i2 <=1) return 1+i2*(i1-1); 

那麼負號i2呢?

if(i2 < 0) return 1/power(i1,-i2); 

谷歌「的libm/exp.c」在C標準庫指數的專業的實現,也有不同的變體,同樣爲「的libm/pow.c」。