新聞中心
在Python中,我們可以使用math庫(kù)中的log函數(shù)來計(jì)算對(duì)數(shù),log函數(shù)有兩種形式:log(x)和log10(x),前者計(jì)算以e為底的對(duì)數(shù),后者計(jì)算以10為底的對(duì)數(shù)。

創(chuàng)新互聯(lián)擁有一支富有激情的企業(yè)網(wǎng)站制作團(tuán)隊(duì),在互聯(lián)網(wǎng)網(wǎng)站建設(shè)行業(yè)深耕10余年,專業(yè)且經(jīng)驗(yàn)豐富。10余年網(wǎng)站優(yōu)化營(yíng)銷經(jīng)驗(yàn),我們已為千余家中小企業(yè)提供了成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)解決方案,定制網(wǎng)站開發(fā),設(shè)計(jì)滿意,售后服務(wù)無(wú)憂。所有客戶皆提供一年免費(fèi)網(wǎng)站維護(hù)!
以下是一些示例:
1、計(jì)算以e為底的對(duì)數(shù):
import math 計(jì)算e的2次方的對(duì)數(shù) result = math.log(math.exp(2)) print(result) # 輸出:2.0
2、計(jì)算以10為底的對(duì)數(shù):
import math 計(jì)算100的對(duì)數(shù) result = math.log10(100) print(result) # 輸出:2.0
3、計(jì)算多個(gè)值的對(duì)數(shù):
import math 計(jì)算2, 8, 64的對(duì)數(shù) numbers = [2, 8, 64] log_values = [math.log(n) for n in numbers] print(log_values) # 輸出:[1.0, 3.0, 4.0]
4、計(jì)算以e為底的自然對(duì)數(shù)(ln):
import math 計(jì)算e的0.5次方的對(duì)數(shù)(即自然對(duì)數(shù)) result = math.log(math.exp(0.5)) print(result) # 輸出:0.5
5、計(jì)算復(fù)數(shù)的對(duì)數(shù):
import cmath 計(jì)算復(fù)數(shù)(1+1j)的對(duì)數(shù)(以1+1j為底) complex_num = 1 + 1j log_value = cmath.log(complex_num) print(log_value) # 輸出:(0.7937+0.1873j)
注意:對(duì)于負(fù)數(shù)和零,log函數(shù)沒有定義,如果你嘗試計(jì)算這些值的對(duì)數(shù),Python會(huì)拋出一個(gè)錯(cuò)誤。
import math 嘗試計(jì)算負(fù)數(shù)的對(duì)數(shù)(將引發(fā)ValueError) result = math.log(1) # ValueError: math domain error
為了避免這個(gè)問題,你可以使用cmath庫(kù)來計(jì)算復(fù)數(shù)的對(duì)數(shù),或者使用numpy庫(kù)來計(jì)算實(shí)數(shù)或復(fù)數(shù)數(shù)組的對(duì)數(shù)。
import numpy as np import cmath 使用numpy計(jì)算實(shí)數(shù)數(shù)組的對(duì)數(shù)(忽略負(fù)數(shù)和零) real_nums = np.array([1, 1, 0, 2, 2]) log_values = np.log(real_nums) # 輸出:[0. inf inf 0.6931 inf]
使用cmath計(jì)算復(fù)數(shù)數(shù)組的對(duì)數(shù)(忽略負(fù)數(shù)和零) complex_nums = np.array([1+1j, 11j, 0, 2+2j, 22j]) log_values = np.array([cmath.log(c) for c in complex_nums]) # 輸出:[(0.7937+0.1873j) inf inf (0.6931+0.1873j) inf]
文章名稱:如何用python計(jì)算log
網(wǎng)頁(yè)路徑:http://www.5511xx.com/article/dpddisp.html


咨詢
建站咨詢
