Math.pow用法及實現探究


pow函數在java.lang.Math類中,是求次方的函數,定義為:

public static double pow(double a, double b);

即求a的b次方,例如:

public static void main(String[] args) {
    double a = 2.0D;
    double b = 4.0D;
    double r = Math.pow(a, b);
    System.out.println(r);
    //輸出為16.0      
}

查看源碼,發現其實現調用了StrictMath類的pow函數,並且,Math中很多函數都調是直接調用了StrictMath類中的函數,而在StrictMath類中方法用native修飾,表明調用的並非java代碼,而是其它的。經了解,這里是C代碼來實現這些方法的,而這些源碼在jdk中並沒有公布。

遂思考如何用java來實現呢?最先想到用循環和遞歸兩種方式可實現。如下:

為簡化邏輯實現,只考慮了自然數(0和正整數)次冪。

1、循環實現:

static int mypow(int x, int y)    
    {   
        if(y < 0){
            return 0;
        }    
        if(y == 0){
            return 1;
        } 
        if(y == 1){
            return x;
        }
        int result = x;
        for (int i = 1; i < y; i++) {
            result *= x;
        }
        return result;    
    }

 

2、遞歸實現:

static int mypow(int x, int y)    
    {    
        if(y < 0){
            return 0;
        }    
        if(y == 0){
            return 1;
        } 
        if(y == 1){
            return x;
        }
        int result = 0;    
        int tmp = mypow(x, y/2);    
        if(y % 2 != 0) //奇數    
        {    
            result = x * tmp * tmp;    
        }else{    
            result = tmp * tmp;    
        }    
        return result;    
    }  

 

注:本文所述內容基於JDK1.7。

 

水平有限,上述觀點難免有誤,僅供參考。歡迎牛們拍磚!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM