Skip to Content

Solved: How do I fix Python exception ValueError: “math domain error”?

Problem Symptom

The Python code works fine in runtime but returns a math domain error in the console. The detailed error message is as below:

error: math domain error
ValueError: Mathematics Domain Error

Solved: How do I fix Python exception ValueError: math domain error?

Solved: How do I fix Python exception ValueError: math domain error?

Solved: How do I fix Python exception ValueError: math domain error?

Follow the below solution steps to resolve the Python exception ValueError: math domain error issue.

Cause

Pythons ValueError: mathematical domain mistakes intensify when using a number that experts say is not supported by mathematical processes. For example some of the mathematics operations like sqrt() , log(), protocol() etc. method, don’t support negative or zero values.

In the mathematical domain of Python, the value is the information stored in the object. You will encounter a ValueError in Python if you use a built-in function or an operation function that takes an on the argument of the correct type but with a clearly inappropriate value.

Python catches this error when you try to do something that was impossible or mathematically defined in the previous statistics.

If you perform the operation with a negative value such as calculating the square root of a negative number, Python will throw an exception error with the message “ValueError: Mathematics Domain Error” during runtime.

For example below, we will try to create a 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))

After passing the value as -1 it returns the runtime exception error as “ValueError: math domain error“.

Another example if you try to calculate a negative base value raised to a fractional power, it will lead to the occurrence of ValueError: math domain error as well.

import math
e = -1.7
print(math.pow(-3, e))

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/Math Error.py”, line 3, in
print(math.pow(-3, e))
ValueError: math domain error

The ValueError: math domain error is produced when a function is being asked to calculate a value using parameters that don’t make sense for the calculation. For example, you ask for the log of a negative number, or a hypotenuse that’s shorter than one of the other two sides.

Solution 1: Add a small value for lower bound

ValueError: math domain exception error occurs when try to fit time-series data into Ornstein-Uhlenbeck (OU) process due to sigma_tilde_squared == 0.

To address the division by 0, you could add 0.01 at the add or set a very small value for the lower bound for mu and sigma (e.g. 1×10^-5) to avoid it == 0. Refer here for the algorithm in action.

Solution 2: Impose minimum pg_num

The ValueError: math domain exception error occurs with deployment due to a low number of OSD’s – a number of pools in the ceph radosgw pool setup get 0.1% of the storage available, so the pg_num calculation based on the number of OSD’s in the cluster ends up == 0.

We should impose a minimum pg_num to prevent this error.

Solution 3: Prevent complex number

list.append(num-i) will result in negative numbers. For real numbers, the root of a negative number does not exist. Since the number is negative by the last assignment, the square root of negative number math.sqrt(num2) is a complex number.

Solved: How do I fix Python exception ValueError: math domain error?

Make sure to check the discriminant value and deal with them accordingly if you want to make a program that can handle both real and imaginary roots. The sqrt function isn’t programmed to handle complex numbers.(i.e when b²-4ac becomes negative). Complex numbers are stored in the form of “a+bj” as per the inbuilt complex datatype.

Solution 4: Use cmath (Mathematical functions for complex numbers) function

math module will not be able to resolve square root of negative number, use cmath module instead. The cmath module allows Python to compute the square root of negative numbers and generate imaginary numbers as output. Imaginary numbers are stored in the form of “a+bj” as per the inbuilt complex datatype.

Sample code:

from cmath import sqrt
print(sqrt(-5))

Output:

2.23606797749979j

Another sample:

from cmath import exp,log
e = -1.7
print(exp(e * log(-3)))

Output:

(0.0908055832509843+0.12498316306449488j)

Solution 5: Apply IF statement condition check

Apply a condition to check for negative values in case any negative values pass by the user then display a message regarding this operation is not allow for negative values.

The sample code as below:

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")

Solution 6: Apply Exception Handling try-except blocks

With try-except blocks, whenever Python hit the ValueError: math domain error, it will be handled by the except block.

Sample code:

from math import *
x = int(input('Enter an integer: '))
try:
print(sqrt(x))
except ValueError:
print("Cannot Compute Negative Square roots!")

Output:

Enter an integer: -5
Cannot Compute Negative Square roots!

In the above sample code, when we enter a positive value we will get the desired output. But, when we enter a negative value it’ll throw “ValueError: math domain error”. The try and except block handle the error by displaying the message “Cannot Compute Negative Square roots!”

Solution 7: Use from __future__ import division function

Consider the following example if you are working on Python 2.x while using log():

import math
print(2/3*math.log(2/3,2))

Output:

Traceback (most recent call last):
File “main.py”, line 2, in
print(2/3*math.log(2/3,2))
ValueError: math domain error

In Python 2.x, 2/3 evaluates to 0 since division floors by default. Therefore you’re attempting a log 0, hence the error. Python 3, on the other hand, does floating-point division by default.

Call from __future__ import division function to avoid the error which gives you Python 3 division behaviour in Python 2.7.

Solution 8: Passing a valid number

Some math operations in Python such as math.asin() and math.acos() method only accepts numbers between the range of -1 to 1. “ValueError: math domain error” occurs if you provide a number beyond this range, or “TypeError: a float is required” error if you provide anything else other than a number.

Sample code:

import math
k = 5
print("asin(",k,") is = ", math.asin(k))

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 4, in
print(“asin(“,k,”) is = “, math.asin(k))
ValueError: math domain error

In order to avoid this error, you can pass a valid input number to the function that lies within the range of -1 and 1.

Sample code:

import math
k = 0.25
print("asin(",k,") is = ", math.asin(k))

Output:

asin( 0.25 ) is = 0.25268025514207865

Reference

Tags

Tags

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker.