Python log()函数来计算对数

时间:2020-02-23 14:42:57  来源:igfitidea点击:

对数用于描述和表示大数。
对数是指数的倒数。
本文将深入探讨Python log()函数。
Python的对数函数可帮助用户以更容易和有效的方式查找数字的对数。

了解Python中的log()函数

为了使用Log函数的功能,我们需要使用以下语句导入math模块。

import math

我们所有人都需要注意以下事实:无法直接访问Python Log函数。
我们需要使用"数学"模块来访问代码中的日志功能。

语法:

math.log(x)

" math.log(x)"函数用于计算自然对数值,即记录到传递给它的参数值(数字表达式)的底e(欧拉数)约为2.71828。

例:

import math   

print("Log value: ", math.log(2))

在上面的代码段中,我们要求对数值为2。

输出:

Log value:  0.6931471805599453

Python log()函数的变体

以下是Python中基本日志功能的变体:

  • log2(x)
  • log(x,基本)
  • log10(x)
  • log1p(x)

1. log2(x)–以2为底的对数

函数math.log2(x)用于计算以2为底的数字表达式的对数值。

语法:

math.log2(numeric expression)

例:

import math 

print ("Log value for base 2: ") 
print (math.log2(20)) 

输出:

Log value for base 2: 
4.321928094887363

2. log(n,Base)–以n为底的对数

math.log(x,Base)函数计算x的对数值,即特定(所需)基值的数字表达式。

语法:

math.log(numeric_expression,base_value)

此函数接受两个参数:

  • 数值表达式
  • 基本值

注意:如果没有为函数提供基值,则math.log(x,(Base))充当基本对数函数,并计算数字表达式对基e的对数。

例:

import math 

print ("Log value for base 4 : ") 
print (math.log(20,4)) 

输出:

Log value for base 4 : 
2.1609640474436813

3. log10(x)–以10为底的对数

" math.log10(x)"函数可将数字表达式的对数值计算为以10为底的数字。

语法:

math.log10(numeric_expression)

例:

import math 

print ("Log value for base 10: ") 
print (math.log10(15)) 

在上面的代码片段中,计算了以10为底的对数值15。

输出:

Log value for base 10 : 
1.1760912590556813

4. log1p(x)

math.log1p(x)函数计算特定输入值即x的log(1 + x)

注意:math.log1p(1 + x)等同于math.log(x)

语法:

math.log1p(numeric_expression)

例:

import math 

print ("Log value(1+15) for x = 15 is: ") 
print (math.log1p(15)) 

在上面的代码片段中,计算了输入表达式15的对数值(1 + 15)。

因此,math.log1p(15)等同于math.log(16)。

输出:

Log value(1+15) for x = 15 is: 
2.772588722239781

了解Python NumPy中的日志

Python NumPy使我们能够同时计算输入NumPy数组元素的自然对数值。

为了使用numpy.log()方法,我们需要使用以下语句导入NumPy模块。

import numpy

语法:

numpy.log(input_array)

numpy.log()函数接受输入数组作为参数,并返回其中元素为对数的数组。

例:

import numpy as np 

inp_arr = [10, 20, 30, 40, 50] 
print ("Array input elements:\n", inp_arr) 

res_arr = np.log(inp_arr) 
print ("Resultant array elements:\n", res_arr) 

输出:

Array input elements:
 [10, 20, 30, 40, 50]
Resultant array elements:
 [ 2.30258509  2.99573227  3.40119738  3.68887945  3.91202301]