Advertisement
Advertisement

## ValueError: math domain error

### Question

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?

2014/02/18
1
102
2/18/2014 1:26:13 PM

### Accepted Answer

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.

2017/09/03
131
9/3/2017 8:49:58 PM

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. `log(0)` means that something raised to the power of `2` is `0`. An exponent can never result in `0`*, which means that `log(0)` has no answer, thus throwing the `math domain error`

*Note: `0^0` can result in `0`, but can also result in `1` at the same time. This problem is heavily argued over.

2019/07/01

You may also use `math.log1p`.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using `math.expm1` which returns `e` raised to the power x, minus 1.

2020/02/10

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

2020/06/23

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]