Python function for log

Функция log() в Python

Логарифмы используются для изображения и представления больших чисел. Журнал – это величина, обратная экспоненте. В этой статье мы подробно рассмотрим функции log(). Логарифмические функции в Python помогают пользователям находить логарифм чисел намного проще и эффективнее.

Понимание функции

Чтобы использовать функциональные возможности журнала, нам необходимо импортировать модуль math, используя приведенный ниже оператор.

Нам всем необходимо принять во внимание тот факт, что к функциям журнала нельзя получить прямой доступ. Нам нужно использовать модуль math для доступа к функциям журнала в коде.

Функция math.log(x) используется для вычисления натурального логарифмического значения, т.е. логарифма с основанием e (число Эйлера), которое составляет около 2,71828 переданного ему значения параметра (числовое выражение).

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

В приведенном выше фрагменте кода мы запрашиваем логарифмическое значение 2.

Log value: 0.6931471805599453

Варианты функций

Ниже приведены варианты базовой функции журнала в Python:

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))

В приведенном выше фрагменте кода вычислено логарифмическое значение от 15 до основания 10.

Log value for base 10 : 1.1760912590556813

4. log1p(x)

Функция math.log1p(x) вычисляет журнал (1 + x) определенного входного значения, т.е. x.

Читайте также:  Найти строку в файле python

Примечание: 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))

В приведенном выше фрагменте кода вычисляется значение журнала (1 + 15) для входного выражения 15.

Таким образом, math.log1p(15) эквивалентен math.log(16).

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

Понимание журнала в NumPy

NumPy позволяет нам одновременно вычислять натуральные логарифмические значения входных элементов массива NumPy.

Чтобы использовать метод numpy.log(), нам нужно импортировать модуль NumPy, используя приведенный ниже оператор.

Функция 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]

Источник

Log functions in Python

Python offers many inbuilt logarithmic functions under the module “math” which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article.
1. log(a,(Base)) : This function is used to compute the natural logarithm (Base e) of a. If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base).

Syntax : math.log(a,Base) Parameters : a : The numeric value Base : Base to which the logarithm has to be computed. Return Value : Returns natural log if 1 argument is passed and log with specified base if 2 arguments are passed. Exceptions : Raises ValueError if a negative no. is passed as argument.

Python3

Natural logarithm of 14 is : 2.6390573296152584 Logarithm base 5 of 14 is : 1.6397385131955606

2. log2(a) : This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2).

Syntax : math.log2(a) Parameters : a : The numeric value Return Value : Returns logarithm base 2 of a Exceptions : Raises ValueError if a negative no. is passed as argument.

Python3

Logarithm base 2 of 14 is : 3.807354922057604

3. log10(a) : This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10).

Syntax : math.log10(a) Parameters : a : The numeric value Return Value : Returns logarithm base 10 of a Exceptions : Raises ValueError if a negative no. is passed as argument.

Python3

Logarithm base 10 of 14 is : 1.146128035678238

3. log1p(a) : This function is used to compute logarithm(1+a) .

Syntax : math.log1p(a) Parameters : a : The numeric value Return Value : Returns log(1+a) Exceptions : Raises ValueError if a negative no. is passed as argument.

Python3

Logarithm(1+a) value of 14 is : 2.70805020110221

1. ValueError : This function returns value error if number is negative.

Читайте также:  Python фильтрация двумерного массива

Python3

Runtime Error :

Traceback (most recent call last): File "/home/8a74e9d7e5adfdb902ab15712cbaafe2.py", line 9, in print (math.log(-14)) ValueError: math domain error

One of the application of log10() function is that it is used to compute the no. of digits of a number. Code below illustrates the same.

Python3

The number of digits in 73293 are : 5

The natural logarithm (log) is an important mathematical function in Python that is frequently used in scientific computing, data analysis, and machine learning applications. Here are some advantages, disadvantages, important points, and reference books related to log functions in Python:

Advantages:

The log function is useful for transforming data that has a wide range of values or a non-normal distribution into a more normally distributed form, which can improve the accuracy of statistical analyses and machine learning models.
The log function is widely used in finance and economics to calculate compound interest, present values, and other financial metrics.
The log function can be used to reduce the effect of outliers on statistical analyses by compressing the scale of the data.
The log function can be used to visualize data with a large dynamic range or with values close to zero.

Disadvantages:

The log function can be computationally expensive for large datasets, especially if the log function is applied repeatedly.
The log function may not be appropriate for all types of data, such as categorical data or data with a bounded range.

Important points:

  1. The natural logarithm (log) is calculated using the numpy.log() function in Python.
  2. The logarithm with a base other than e can be calculated using the numpy.log10() or numpy.log2() functions in Python.
  3. The inverse of the natural logarithm is the exponential function, which can be calculated using the numpy.exp() function in Python.
  4. When using logarithms for statistical analyses or machine learning, it is important to remember to transform the data back to its original scale after analysis.
Читайте также:  Check if php cgi

Reference books:

“Python for Data Analysis” by Wes McKinney covers the NumPy library and its applications in data analysis in depth, including the logarithmic function.
“Numerical Python: A Practical Techniques Approach for Industry” by Robert Johansson covers the NumPy library and its applications in numerical computing and scientific computing in depth, including the logarithmic function.
“Python Data Science Handbook” by Jake VanderPlas covers the NumPy library and its applications in data science in depth, including the logarithmic function.

This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Источник

Оцените статью