valueerror: math domain error – Code Example

Total
0
Shares

In this article we will resolve valueerror: math domain error using Python code examples. This error is generally raised by log() and sqrt() function of Python math library. If you provide any invalid value like -1 or 0 to the log() function, it will raise the error.

Why this error is raised?

The error says “math domain error” which means there is some issue with domain. In mathematics we have two things – domain and range. Domain is the set of acceptable input values for a function and range is the set of output generated by the function. So, sin() has range of -1 to 1. Although its domain is any radian value.

In case of log(), 0 and negative numbers can’t be given as input. Understand it this way –

log(x) = y, which is equal to –
x = ey
i.e., y√x = e

Now suppose x = -1, then, y√-1 = e

Root of a negative number is not a real number. This is a problem. The domain, -1, is not appropriate for log(). Same applies for sqrt().

Code Example

Error Code – Let’s first reproduce the error –

import math

print(math.log(-1))

This will throw the error –

Traceback (most recent call last):
  File "/home/jdoodle.py", line 5, in <module>
    print(math.log(-1))
ValueError: math domain error

Solution

The only solution to this issue is to avoid using invalid domain for math functions. For log() & sqrt() avoid using negative numbers. Use try...except block to catch exception –

import math

print(math.log(5))

try:
    print(math.log(-1))
except:
    print("Invalid value in log function")

Output –

1.6094379124341003
Invalid value in log function

Live Demo

Open Live Demo