Python логарифм по произвольному основанию

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.

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:

Читайте также:  Opencart admin config php

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.

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.

Источник

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

Читайте также:  К python and sas

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.

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

Источник

Python log() Functions to Calculate Logarithm

Python log() Functions to Calculate Logarithm

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Logarithms are used to depict and represent large numbers. The log is an inverse of the exponent. This article will dive into the Python log() functions. The logarithmic functions of Python help the users to find the log of numbers in a much easier and efficient manner.

Understanding the log() functions in Python

In order to use the functionalities of Log functions, we need to import the math module using the below statement.

We all need to take note of the fact that the Python Log functions cannot be accessed directly. We need to use the math module to access the log functions in the code. Syntax:

Читайте также:  Cpp cli winforms project

The math.log(x) function is used to calculate the natural logarithmic value i.e. log to the base e (Euler’s number) which is about 2.71828, of the parameter value (numeric expression), passed to it. Example:

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

Variants of Python log() Functions

  • log2(x)
  • log(x, Base)
  • log10(x)
  • log1p(x)

1. log2(x) — log base 2

The math.log2(x) function is used to calculate the logarithmic value of a numeric expression of base 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) — log base n

The math.log(x,Base) function calculates the logarithmic value of x i.e. numeric expression for a particular (desired) base value.

math.log(numeric_expression,base_value) 

This function accepts two arguments:

Note: If no base value is provided to the function, the math.log(x,(Base)) acts as a basic log function and calculates the log of the numeric expression to the 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) — log base 10

The math.log10(x) function calculates the logarithmic value of the numeric expression to the base 10.

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

In the above snippet of code, the logarithmic value of 15 to the base 10 is calculated.

Log value for base 10 : 1.1760912590556813 

4. log1p(x)

The math.log1p(x) function calculates the log(1+x) of a particular input value i.e. x

Note: math.log1p(1+x) is equivalent to math.log(x)

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

In the above snippet of code, the log value of (1+15) for the input expression 15 is calculated.

Thus, math.log1p(15) is equivalent to math.log(16) .

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

Understanding log in Python NumPy

Python NumPy enables us to calculate the natural logarithmic values of the input NumPy array elements simultaneously.

In order to use the numpy.log() method, we need to import the NumPy module using the below statement.

The numpy.log() function accepts input array as a parameter and returns the array with the logarithmic value of elements in it.

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] 

Conclusion

In this article, we have understood the working of Python Log functions and have unveiled the variants of the logarithmic function in Python.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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