티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Why does math.log result in ValueError: math domain error?

왜 math.log 함수는 ValueError: math domain error를 발생시키나요?

 문제 내용 

I was just testing an example from Numerical Methods in Engineering with Python.

저는 'Numerical Methods in Engineering with Python'에서 예제를 테스트하고 있었습니다.

 

from numpy import zeros, array
from math import sin, log
from newtonRaphson2 import *

def f(x):
    f = zeros(len(x))
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
    f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0
    f[2] = x[0] + x[1] + x[2] -5.0
    return f
    
x = array([1.0, 1.0, 1.0])
print(newtonRaphson2(f,x))

When I run it, it shows the following error:

프로그램을 실행하면 다음과 같은 오류가 표시됩니다.

 

File "example NR2method.py", line 8, in f
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
ValueError: math domain error

I have narrowed it down to the log as when I remove log and add a different function, it works. I assume it is because of some sort of interference with the base, I can't figure out how. Can anyone suggest a solution?

로그를 제거하고 다른 함수를 추가하면 작동하기 때문에 로그 때문인 것 같습니다. 그러나 어떤 문제로 인해 이런 오류가 발생하는 지 파악할 수 없습니다. 해결책을 제안할 수 있는 분이 있을까요?

 


See also: Python math domain error using math.acos function for the equivalent problem using math.acos; python math domain error - sqrt for the equivalent problem using math.sqrt.

참고: math.acos 함수를 사용한 Python math domain error 및 math.sqrt 함수를 사용한 python math domain error - sqrt와 같은 문제에 대한 동등한 문제가 있습니다.

 

 

 

 높은 점수를 받은 Solution 

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

당신의 코드는 0보다 작거나 같은 숫자의 로그를 구하고 있습니다. 수학적으로 정의되지 않은 값이므로 Python의 log 함수는 예외를 발생시킵니다. 다음은 그 예시입니다:

 

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

newtonRaphson2 함수가 무엇을 하는지 모르기 때문에, 잘못된 x[2] 값이 어디에서 왔는지 추측할 수 없지만, 이 정보가 올바른 방향으로 이끌어줄 수 있기를 바랍니다.

 

 

 

 가장 최근 달린 Solution 

We face this problem when we use log() or sqrt() from math library. In this problem “math domain error”, we are using a negative number like (-1 or another) or a zero number where we should not be use.

"math domain error"이라는 문제는 math 라이브러리에서 log()나 sqrt() 함수를 사용할 때 발생합니다. 이 문제에서는 (-1 또는 다른 음수)와 같은 음수 또는 우리가 사용해서는 안되는 0과 같은 수를 사용합니다.

 

 

 

출처 : https://stackoverflow.com/questions/15890503/why-does-math-log-result-in-valueerror-math-domain-error

반응형
댓글
공지사항
최근에 올라온 글