[Solved] ValueError: math domain error


In Python, some of the mathematics operation doesn’t support negative or zero values. In this case when you perform operation with negative value then on runtime Python throws exception as “ValueError: Mathematics Domain Error” .

Here are some operations like sqrt() , log() etc. method which doesn’t work with negative values.

Example:

In this below example, we will try to create scenario by passing both positive and negative numbers and see the results.

import math

number = input("Please insert a number: ")

square=math.sqrt(int(number))

print("Square of number "+str(number) +" is :"+str(square))

Output

Passing Positive Number : 5

Please insert a number: 5
Square of number 5 is :2.23606797749979

Passing Negative Number: -5

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 5, in
square=math.sqrt(int(number))

ValueError: math domain error

After passing the value as -5 it’s throwing the runtime exception as “ValueError:math domain error“.

Solution

The solution to handle such situation is apply condition which check for negative values in case any negative values pass by user the show message to user as this operation is not allow for negative values.

import math

number = input("Please insert a number: ")
if(int(number)>0):
    square=math.sqrt(int(number))
    print("Square of number "+str(number) +" is :"+str(square))
else:
    print("Negative values are not allow for SQRT() operation")

Output

Passing Positive Number : 5

Please insert a number: 5
Square of number 5 is :2.23606797749979

Passing Negative Number : -5

Please insert a number: -5
Negative values are not allow for SQRT() operation

If you noticed from above program in solution, I just put one condition to check the value of input number to resolve the problem “ValueError: math domain error

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s