當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Perl log()用法及代碼示例


Perl中的log()函數返回傳遞給它的值的自然對數。如果調用時未傳遞值,則返回$_。 log()函數可用於使用以下公式查找任何底數的對數:

用法: log(value)

參數:
value:要計算的日誌數


返回:
標量上下文中的浮點數

範例1:

#!/usr/bin/perl -w 
  
# Calculating log of base 10  
# using log function 
print "log10(2): ", log10(2), "\n"; 
print "log10(7): ", log10(7), "\n"; 
print "log10(9): ", log10(9), "\n"; 
  
# Function for log10 calculator 
sub log10  
{ 
    my $n = shift; 
      
    # using pre-defined log function 
    return log($n) / log(10); 
}

輸出:

log10(2): 0.301029995663981
log10(7): 0.845098040014257
log10(9): 0.954242509439325


範例2:

#!/usr/bin/perl -w 
  
# Calculating log of different  
# base using log function 
print "log3(2): ", log3(2), "\n"; 
print "log5(7): ", log5(7), "\n"; 
print "log2(9): ", log2(9), "\n"; 
  
# Function for log3 calculator 
sub log3  
{ 
    my $n = shift; 
      
    # using pre-defined log function 
    return log($n) / log(3); 
} 
  
# Function for log5 calculator 
sub log5 
{ 
    my $n = shift; 
      
    # using pre-defined log function 
    return log($n) / log(5); 
} 
  
# Function for log2 calculator 
sub log2  
{ 
    my $n = shift; 
      
    # using pre-defined log function 
    return log($n) / log(2); 
}

輸出:

log3(2): 0.630929753571457
log5(7): 1.20906195512217
log2(9): 3.16992500144231


相關用法


注:本文由純淨天空篩選整理自Code_Mech大神的英文原創作品 Perl | log() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。