The Wayback Machine - https://web.archive.org/web/20240821211916/https://www.geeksforgeeks.org/python-value-error-math-domain-error-in-python/
Open In App

Python Value Error :Math Domain Error in Python

Last Updated : 02 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Errors are the problems in a program due to which the program will stop the execution. One of the errors is ‘ValueError: math domain error’ in Python. In this article, you will learn why this error occurs and how to fix it with examples.

What is ‘ValueError: math domain error’ in Python?

In mathematics, we have certain operations that we consider undefined. Undefined refers to a term that is mathematically inexpressible. The most common examples of undefined operations in mathematics are:

  • A division by zero (For example 45/0)
  • The square root of negative numbers (For example: √-67)
  • The log of a negative number (For example log(-3))

When you perform such undefined operations or operations that fall outside the domain in Python, you encounter an error – ‘ValueError: math domain error’. A domain in mathematics refers to a range of all possible values a function accepts. When a function in Python is provided with a value outside the domain, ‘ValueError: math domain error’ occurs.

How to Fix “ValueError: math domain error” in Python?

Let us now discuss different scenarios where this error occurs and the respective solution to help you understand how to resolve the error.

math.sqrt()

Python has the math.sqrt() function that provides the square root of a number. However, the number should be greater than or equal to 0. If you provide a number less than 0, i.e., a negative number, the Python interpreter throws the error – ‘ValueError: math domain error’.

Python




import math
print math.sqrt(-9)


Output Error:

Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 2, in <module>
    print math.sqrt(-9)
ValueError: math domain error

Solution:

The simple solution to avoid this error is to use the ‘if-else’ statement to check whether the entered number is negative or not. If it is not negative, the math.sqrt() function will provide the desired output. If the number is negative, it will display the message on the screen that a negative number cannot be used.

Here is how you can do it:

Python3




import math
num = int(input('Enter the number:'))
if num >= 0:
    ans = math.sqrt(num)
    print(f"The square root of the {} is {ans}")
else:
    print("The entered number is negative and cannot find the square root.")


Output 1:

Enter the number: 5
The square root of 5 is 2.23606797749979

Output 2:

Enter the number: -5
The entered number is negative and cannot find the square root.

math.log ()

The Python function math.log() provides the logarithm of a given number. However, it only accepts a number greater than 0. If you use a negative number and even 0, Python raises the error – ValueError: math domain error.

Python3




import math
print (math.log(0))


Output Error:

Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 2, in <module>
    print (math.log(0))
ValueError: math domain error

Solution:

As we did in the above example, we will use the same if-else statement to avoid the ValueError.

Python3




import math
num = int(input("Enter the number: "))
if num > 0:
  result = math.log(num)
  print(f"The log of {} is {res}")
else:
  print("Cannot find the log of 0 or a negative number")


Output 1:

Enter the number: 4
The log of 4 is 1.3862943611198906

Output 2:

Enter the number: -5
Cannot find the log of 0 or a negative number

math.acos()

The math.acos() method gives the arc cosine value of a number. The range of this function is from -1 to 1. So, any number outside this range provided to this function will raise the error – ValueError: math domain error.

Python3




import math
print(math.acos(5))


Output Error:

Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 2, in <module>
    print(math.acos(5))
ValueError: math domain error

Solution:

Python3




import math
num = int(input('Enter the number: '))
if -1 <= num <= 1:
    result = math.acos(num)
    print(f'The arc cosine of {num} is {result}')
else:
    print('Cannot find the arc cosine of any number other than ones between -1 and 1.')


Output 1

Enter the number: 1
The arc cosine of 1 is 0.0

Output 2

Enter the number: -3
Cannot find the arc cosine of any number other than ones between -1 and 1.

In a nutshell, when you use a number that is out of the range for a specific math function in Python, you will receive the error – ‘ValueError: math domain error’. Use proper conditional statements to handle the function and the values.



Similar Reads

Python Overflowerror: Math Range Error
Python is a powerful and versatile programming language, widely used for various applications. However, developers may encounter errors during the coding process. One such error is the 'OverflowError: Math Range Error.' This article will explore what this error is, discuss three common reasons for encountering it, and provide approaches to resolve
4 min read
Python | Sorting URL on basis of Top Level Domain
Given a list of URL, the task is to sort the URL in the list based on the top-level domain. A top-level domain (TLD) is one of the domains at the highest level in the hierarchical Domain Name System of the Internet. Example - org, com, edu. This is mostly used in a case where we have to scrap the pages and sort URL according to top-level domain. It
3 min read
Full domain Hashing with variable Hash size in Python
A cryptographic hash function is a special class of hash function that has certain properties which make it suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash function) which is designed to also be a one-way function, that is, a function which is infeasible to in
5 min read
Create a GUI to find the IP for Domain names using Python
Prerequisite: Python GUI – tkinter In this article, we are going to see how to find IP from Domain Names and bind it with GUI Application using Python. We will use iplookup module for looking up IP from Domain Names. It is a small module which accepts a single domain as a string, or multiple domains as a list, and returns a list of associated IP. R
2 min read
Writing a Domain Specific Language (DSL) in Python
The Domain Specific Languages (DSLs) are specialized programming languages tailored to specific problem domains or application areas. They enable developers to express domain-specific concepts and operations in concise intuitive syntax enhancing productivity and readability. In this article, we'll explore the process of designing and implementing a
3 min read
How to Navigating the "Error: subprocess-exited-with-error" in Python
In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to resolve it with different approaches. We will also p
4 min read
Create a GUI to check Domain Availability using Tkinter
There might be a case where a user wants to create a website and having certain ideas for the website's name but is struck on their availability. So let's develop a GUI that will check for domain availability. We will use the Python-whois module to get information about the website. It's able to extract data for all the popular TLDs (com, org, net,
2 min read
Create a GUI to Get Domain Information Using Tkinter
Prerequisites: Python GUI – tkinter Domain information is very important for every user. It contains information like Name, organization, State, city, Ip address, emails, server name, etc. In this article, we will write code for getting domain information and bind it with GUI Application. We will use the Python-whois module to get information about
2 min read
Get the Absolute URL with Domain in Django
When developing web applications, generating the full URL (including the domain) is often necessary. For instance, sending confirmation emails with links, generating sitemaps, or creating social media share links require absolute URLs. Django provides several utilities and methods to achieve this seamlessly. We'll start by setting up a Django proje
3 min read
PyQtGraph – Getting Co-ordinate Value of Error Bar Graph
In this article, we will see how we can get a co-ordinate value of the error bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, vid
3 min read
PyQtGraph – Setting Origin Value of Error Bar Graph
In this article, we will see how we can set the co-ordinate value of the error bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, v
3 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python math function | modf()
modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float. Syntax : modf(number) Time Complexity: O(1) Auxiliary Space: O(1) Parameter : There is only one mandatory parameter which is the numbe
3 min read
Python math function | hypot()
hypot() function is an inbuilt math function in Python that return the Euclidean norm, [Tex]\sqrt{(x*x + y*y)} [/Tex]. Syntax : hypot(x, y) Parameters : x and y are numerical values Returns : Returns a float value having Euclidean norm, sqrt(x*x + y*y). Error : When more than two arguments are passed, it returns a TypeError. Note : One has to impor
2 min read
fabs() method of Python's math Library
fabs() is a method specified in math library in Python 2 and Python 3. Sometimes while computing the difference between 2 numbers to compute the closeness of a number with the other number, we require to find the magnitude of certain number, fabs() can come handy in the cases where we are dealing with ints and want the result in float number to per
3 min read
Python | math.fabs() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.fabs() function returns the absolute value of the number. Syntax: math.fabs(x) Parameter: x: This is a numeric expression. Returns: the absolute value of the number. Time Complexity: O(1) Auxiliary Space: O(1) Code #1: C/C++
1 min read
Python | math.floor() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If number is already integer, same number is returned. Syntax: math.floor(x) Parameter: x: This is a numeric expression. Returns: largest integer not greater th
1 min read
Python math library | expm1() method
Python has math library and has many functions regarding to it. One such function is expm1(). This function mathematically computes the value of exp(x) - 1. This method can be used if we need to compute this very value. Syntax : math.expm1() Parameters : x : Number whose exp(x)-1 has to be computed. Returns : Returns the computed value of "exp(x)-1
2 min read
Python math.gamma() Method
Python in its language allows various mathematical operations, which has manifolds application in scientific domain. One such offering of Python is the inbuilt gamma() function, which numerically computes the gamma value of the number that is passed in the function. Syntax : math.gamma(x) Parameters : x : The number whose gamma value needs to be co
2 min read
Python math function | copysign()
math.copysign() is a function exists in Standard math Library of Python. This function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y. Syntax : math.copysign(x, y) Parameters : x : Integer value to be converted y : Integer whose sign is required Returns : float value consisting of magnitude
1 min read
Python math library | isnan() method
Python has math library and has many functions regarding it. One such function is isnan(). This method is used to check whether a given parameter is a valid number or not. Syntax : math.isnan(x) Parameters : x [Required] : It is any valid python data type or any number. Returns: Return type is boolean. -&gt; Returns False if the given parameter is
1 min read
Python math library | exp() method
Python has math library and has many functions regarding it. One such function is exp(). This method is used to calculate the power of e i.e. e^y or we can say exponential of y. The value of e is approximately equal to 2.71828….. Syntax : math.exp(y) Parameters : y [Required] - It is any valid python number either positive or negative. Note that if
2 min read
Python | math.ceil() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned. Syntax: math.ceil(x) Parameter: x: This is a numeric expression. Returns: Smallest integer no
1 min read
Python | math.factorial() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number. Syntax: math.factorial(x) Parameter: x: This is a numeric expression. Returns: factorial of desired number. Time Complexity: O(n) where n is the input number. Auxi
2 min read
Python | math.copysign() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.copysign(a, b) function return a float with the magnitude (absolute value) of a but the sign of b. Syntax: math.copysign(a, b) Parameter: a, b: numeric values. Returns: Return absolute value of a but the sign of b. Code #1: #
1 min read
Python | math.gcd() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments. Syntax: math.gcd(x, y) Parameter: x : Non-negative integer whose gcd has to be computed. y : Non-negative integer whose gcd has to be
2 min read
Python | math.cos() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.cos() function returns the cosine of value passed as argument. The value passed in this function should be in radians. Syntax: math.cos(x) Parameter: x : value to be passed to cos() Returns: Returns the cosine of value passed
2 min read
Python | math.tan() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.tan() function returns the tangent of value passed as argument. The value passed in this function should be in radians. Syntax: math.tan(x) Parameter: x : value to be passed to tan() Returns: Returns the tangent of value pass
1 min read
Python | math.sin() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.sin() function returns the sine of value passed as argument. The value passed in this function should be in radians. Syntax: math.sin(x) Parameter: x : value to be passed to sin() Returns: Returns the sine of value passed as
1 min read
Python math library | isfinite() and remainder() method
Python has math library and has many functions regarding to it. math.remainder() method returns an exact (floating) value as a remainder. Syntax: math.remainder(x, y) Time Complexity: O(1) Auxiliary space: O(1) For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y.
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg