글 작성자: astrocosmos

Python에서 log 함수는 "math"을 import해서 쓸 수 있다.

import math

밑이 2인 로그 함수 ($ log_2 x$)

import math

print(math.log2(1))  # output: 0.0
print(math.log2(2))  # output: 1.0
print(math.log2(4))  # output: 2.0
print(math.log2(5))  # output: 2.321928094887362

밑이 10인 로그 함수 ($ log_{10} x $)

import math

print(math.log10(1))    # output: 0.0
print(math.log10(2))    # output: 0.3010299956639812
print(math.log10(10))   # output: 1.0
print(math.log10(100))  # output: 2.0

밑이 $ e $인 로그 함수 ($ log_e x $ or $ ln \space x $ or $ log \space x $)

밑이 $ e $인 로그 함수를 자연로그라고 부르고 아래의 세가지 방법으로 표기할 수 있다.

$$ log_e x = ln \space x = log \space x $$

앞의 두가지는 모호함이 없지만, $ log \space x $는 수학분야에서 자연로그로 사용되는 것이 흔하지만, 다른 분야에선 상용로그(밑이 10인 로그, $ log_{10}x $)로 사용되기도 해서 혼동될 수 있다. 하지만, Python의 함수 이름에서도 알 수 있듯이 $ log \space x $가 자연로그로 사용되었다. 참고로, "math.ln()"이라는 함수는 없다.

자연로그의 밑 "$ e $"는 다음의 극한값으로 표현되며, python에서 "math.e"로 간단하게 사용할 수 있다.

$$ e = \lim_{n \to  \infty } \left(1 + \frac{1}{n}\right) ^ n $$

import math

print(math.log(1))                  # output: 0.0
print(math.log(2))                  # output: 0.6931471805599453
print(math.log(2.71828182845904))   # output: 0.9999999999999981
print(math.log(2.718281828459045))  # output: 1.0
print(math.log(math.e))             # output: 1.0
print(math.log(math.e ** 2))        # output: 2.0

자연로그 밑 $ e $에 해당하는 수를 소숫점 아래 14자리를 써도 1.0이 안나오고 소숫점 아래 15자리를 써야 1.0이 나오지만 계산식에 따라 1.0으로 정확하게 계산되지 않을 수도 있으므로 $ e $는 되도록 math.e를 쓰는 것이 좋다.

밑이 2, 10, $ e $가 아닌 로그 함수

밑이 2나 10 또는 $ e $가 아닌 어떤 수로도 로그 함수를 구할 수 있다. 아래의 예제는 밑이 5인 로그 함수이다.

import math

print(math.log(1, 5))          # output: 0.0
print(math.log(2, 5))          # output: 0.43067655807339306
print(math.log(5, 5))          # output: 1.0
print(math.log(5 ** 2, 5))     # output: 2.0
print(math.log(5 ** 3, 5))     # output: 3.0000000000000004
print(math.log(pow(5, 3), 5))  # output: 3.0000000000000004

pow()는 제곱을 구하는 함수라서 '**'와 같은 의미를 가진다. 5의 3 제곱을 $ log_5 5^3 $은 3이 나와야 하지만 정확하게 3.0으로 계산되지 않는 것을 볼 수 있다. 프로그램으로 구할 경우 이런 경우는 충분히 발생할 수 있다. 만약 정확도가 엄청나게 높아야 하는 경우엔 이런 케이스도 고려해야 한다.

 


 

 

math — Mathematical functions — Python 3.9.2 documentation

math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for co

docs.python.org

 

자연로그

위키백과, 우리 모두의 백과사전. 자연로그 함수 그래프 자연로그(自然log, 영어: natural logarithm)는 e를 밑으로 하는 로그를 뜻한다. 즉, e x = y {\displaystyle e^{x}=y} 일 때, ln ⁡ y = x {\displaystyle \ln y=x}

ko.wikipedia.org

 

728x90