AppDividend
Latest Code Tutorials

# How to Solve math domain error in Python

In Python, if you pass the invalid argument to a mathematical function, then it can’t perform the operation and raises the ValueError. In this tutorial, we will see what math domain error is, why we get and how to resolve it.

## Python math domain error

Python ValueError: math domain error is obtained when you use a number that is not supported by a mathematical operation. The ValueError is an error that shows you are executing a mathematical operation on a value that does not work with that operation.

## Why you get a math domain error

If you are using the sqrt() and log() function frequently, then know that this error occurs with these functions more.

To get the math domain error in Python, find the square root of a negative number.

```import math

print(math.sqrt(-9))
```

#### Output

`ValueError: math domain error`

And we get the ValueError: math domain error which suggests that you can not find the square root of a negative number.

## Solved: math domain error

To solve the math domain error in Python, we need to prevent the user so that he cannot calculate the square root of a negative number before we execute the math.sqrt() function.

```import math

data = -11
if int(data) >= 0:
math.sqrt(data)
else:
print("You can not calculate square root of negative number")
```

#### Output

`You can not calculate square root of negative number`

In this example, we used an if statement to check if the input number is negative or not. If it is, then else will execute, and we won’t get the math domain error.

The ValueError: math domain error is thrown when you execute a mathematical operation on the negative or zero number, which cannot be calculated.

If you try to calculate the log of 0(zero), then also math domain error is raised.

```import math

data = 0

math.log(data)```

#### Output

`ValueError: math domain error`

If you pass a valid parameter to the mathematical function, then you won’t get the ValueError. Otherwise, you will get the error, and to prevent that, you need to put some conditions as we did in our example.

That’s it for this tutorial.

This site uses Akismet to reduce spam. Learn how your comment data is processed.