ValueError: math domain error
I was just testing an example from 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 = sin(x) + x**2 + log(x) - 7.0 f = 3.0*x + 2.0**x - x**3 + 1.0 f = x + x + x -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 = sin(x) + x**2 + log(x) - 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?
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:
>>> 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 value is coming from, but hopefully this will lead you on the right track.
★ Back to homepage or read more recommendations: