Содержание
- How to Solve Python ValueError: math domain error
- Table of contents
- ValueError: math domain error
- What is a ValueError?
- Example #1: Square Root of a Negative Number
- Solution #1: Use an if statement
- Solution #2: Use cmath
- Example #2: Logarithm of Zero
- Solution
- Summary
- [Solved] ValueError: Math Domain error in Python
- Introduction
- ⚠️What Is a Math Domain Error in Python?
- Python Math Domain Error (How to Fix This Stupid Bug)
- Python Math Domain Error Sqrt
- Python Math Domain Error Log
- Python Math Domain Error Acos
- Python Math Domain Error Asin
- Python Math Domain Error Pow
- NumPy Math Domain Error — np.log(x)
- Where to Go From Here?
- FLP32-C. Prevent or detect domain and range errors in math functions
- Domain and Pole Checking
- Range Checking
- Subnormal Numbers
- Noncompliant Code Example ( sqrt() )
- Compliant Solution ( sqrt() )
- Noncompliant Code Example ( sinh() , Range Errors)
- Compliant Solution ( sinh() , Range Errors)
- Noncompliant Code Example ( pow() )
- Compliant Solution ( pow() )
- Noncompliant Code Example ( asin() , Subnormal Number)
- Compliant Solution ( asin() , Subnormal Number)
- Risk Assessment
How to Solve Python ValueError: math domain error
The domain of a mathematical function is the set of all possible input values. If you pass an undefined input to a function from the math library, you will raise the ValueError: math domain error.
To solve this error, ensure that you use a valid input for the mathematical function you wish to use. You can put a conditional statement in your code to check if the number is valid for the function before performing the calculation.
You cannot use functions from the math library with complex numbers, such as calculating a negative number’s square root. To do such calculations, use the cmath library.
This tutorial will go through the error in detail and solve it with the help of some code examples.
Table of contents
ValueError: math domain error
What is a ValueError?
In Python, a value is the information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.
The ValueError: math domain error occurs when you attempt to use a mathematical function with an invalid value. You will commonly see this error using the math.sqrt() and math.log() methods.
Example #1: Square Root of a Negative Number
Let’s look at an example of a program that calculates the square root of a number.
We import the math library to use the square root function in the above code. We collect the number from the user using the input() function. Next, we find the square root of the number and print the result to the console using an f-string. Let’s run the code to see the result:
We raise the ValueError because a negative number does not have a real square root.
Solution #1: Use an if statement
To solve this error, we can check the value of the number before attempting to calculate the square root by using an if statement. Let’s look at the revised code:
In the above code, we check if the user’s number is greater than zero. If it is, we calculate the number’s square root and print it to the console. Otherwise, we print a statement telling the user the number is invalid for the square root function. Let’s run the code to see the result:
Go to the article: Python Square Root Function for further reading on calculating the square root of a number in Python.
Solution #2: Use cmath
We can also solve the square root math domain error using the cmath library. This library provides access to mathematical functions for complex numbers. The square root of a negative number is a complex number with a real and an imaginary component. We will not raise a math domain error using the square root function from cmath on a negative number. Let’s look at the revised code:
Let’s run the code to get the result:
Example #2: Logarithm of Zero
Let’s look at an example of a program that calculates the natural logarithm of a number. The log() method returns the natural logarithm of a number or to a specified base. The syntax of the math.log() method is:
Parameters:
- x: Required. The value to calculate the number logarithm for.
- base: Optional. The logarithmic base to use. The default is e.
We import the math library to use the natural logarithm function in the above code. We collect the number from the user using the input() function. Next, we find the natural logarithm of the number and print the result to the console using an f-string. Let’s run the code to see the result:
We raise the ValueError because you cannot calculate the natural logarithm of 0 or a negative number. The log(0) means that the exponent e raised to the power of a number is 0. An exponent can never result in 0, which means log(0) has no answer, resulting in the math domain error.
Solution
We can put an if statement in the code to check if the number we want to use is positive to solve this error. Let’s look at the revised code:
Now we will only calculate the natural logarithm of the number if it is greater than zero. Let’s run the code to get the result:
Summary
Congratulations on reading to the end of this tutorial! ValueError: math domain error occurs when you attempt to perform a mathematical function with an invalid number. Every mathematical function has a valid domain of input values you can choose. For example, the logarithmic function accepts all positive, real numbers. To solve this error, ensure you use input from the domain of a function. You can look up the function in the math library documentation to find what values are valid and which values will raise a ValueError.
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Источник
[Solved] ValueError: Math Domain error in Python
Introduction
So, you sit down, grab a cup of coffee and start programming in Python. Then out of nowhere, this stupid python error shows up: ValueError: math domain error . 😞
Sometimes it may seem annoying, but once you take time to understand what Math domain error actually is, you will solve the problem without any hassle.
To fix this error, you must understand – what is meant by the domain of a function?
Let’s use an example to understand “the domain of a function.”
Given equation : y= √(x+4)
- y = dependent variable
- x = independent variable
The domain of the function above is x≥−4 . Here x can’t be less than −4 because other values won’t yield a real output.
❖ Thus, the domain of a function is a set of all possible values of the independent variable (‘x’) that yield a real/valid output for the dependent variable (‘y’).
⚠️What Is a Math Domain Error in Python?
If you have done something that is mathematically undefined (not possible mathematically), then Python throws ValueError: math domain error .
Источник
Python Math Domain Error (How to Fix This Stupid Bug)
You may encounter a special ValueError when working with Python’s math module.
Python raises this error when you try to do something that is not mathematically possible or mathematically defined.
To understand this error, have a look at the definition of the domain:
“The domain of a function is the complete set of possible values of the independent variable. Roughly speaking, the domain is the set of all possible (input) x-values which result in a valid (output) y-value.” (source)
The domain of a function is the set of all possible input values. If Python throws the ValueError: math domain error , you’ve passed an undefined input into the math function. Fix the error by passing a valid input for which the function is able to calculate a numerical output.
Here are a few examples:
Python Math Domain Error Sqrt
The math domain error appears if you pass a negative argument into the math.sqrt() function. It’s mathematically impossible to calculate the square root of a negative number without using complex numbers. Python doesn’t get that and throws a ValueError: math domain error .
Here’s a minimal example:
You can fix the math domain error by using the cmath package that allows the creation of complex numbers:
Python Math Domain Error Log
The math domain error for the math.log() function appears if you pass a zero value into it—the logarithm is not defined for value 0.
Here’s the code on an input value outside the domain of the logarithm function:
The output is the math domain error:
You can fix this error by passing a valid input value into the math.log() function:
This error can sometimes appear if you pass a very small number into it—Python’s float type cannot express all numbers. To pass a value “close to 0”, use the Decimal module with higher precision, or pass a very small input argument such as:
Python Math Domain Error Acos
The math domain error for the math.acos() function appears if you pass a value into it for which it is not defined—arccos is only defined for values between -1 and 1.
Here’s the wrong code:
The output is the math domain error:
You can fix this error by passing a valid input value between [-1,1] into the math.acos() function:
Python Math Domain Error Asin
The math domain error for the math.asin() function appears if you pass a value into it for which it is not defined—arcsin is only defined for values between -1 and 1.
Here’s the erroneous code:
The output is the math domain error:
You can fix this error by passing a valid input value between [-1,1] into the math.asin() function:
Python Math Domain Error Pow
The math domain error for the math.pow(a,b) function to calculate a**b appears if you pass a negative base value into it and try to calculate a negative power of it. The reason it is not defined is that any negative number to the power of 0.5 would be the square number—and thus, a complex number. But complex numbers are not defined by default in Python!
The output is the math domain error:
If you need a complex number, a b must be rewritten into e b ln a . For example:
You see, it’s a complex number!
NumPy Math Domain Error — np.log(x)
This is the graph of log(x) . Don’t worry if you don’t understand the code, what’s more important is the following point. You can see that log(x) tends to negative infinity as x tends to 0. Thus, it is mathematically meaningless to calculate the log of a negative number. If you try to do so, Python raises a math domain error.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Источник
FLP32-C. Prevent or detect domain and range errors in math functions
The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines three types of errors that relate specifically to math functions in . Paragraph 2 states
A domain error occurs if an input argument is outside the domain over which the mathematical function is defined.
Paragraph 3 states
A pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit.
Paragraph 4 states
A range error occurs if the mathematical result of the function cannot be represented in an object of the specified type, due to extreme magnitude.
An example of a domain error is the square root of a negative number, such as sqrt(-1.0) , which has no meaning in real arithmetic. Contrastingly, 10 raised to the 1-millionth power, pow(10., 1e6) , cannot be represented in many floating-point implementations because of the limited range of the type double and consequently constitutes a range error. In both cases, the function will return some value, but the value returned is not the correct result of the computation. An example of a pole error is log(0.0) , which results in negative infinity.
Programmers can prevent domain and pole errors by carefully bounds-checking the arguments before calling mathematical functions and taking alternative action if the bounds are violated.
Range errors usually cannot be prevented because they are dependent on the implementation of floating-point numbers as well as on the function being applied. Instead of preventing range errors, programmers should attempt to detect them and take alternative action if a range error occurs.
The following table lists the double forms of standard mathematical functions, along with checks that should be performed to ensure a proper input domain, and indicates whether they can also result in range or pole errors, as reported by the C Standard. Both float and long double forms of these functions also exist but are omitted from the table for brevity. If a function has a specific domain over which it is defined, the programmer must check its input values. The programmer must also check for range errors where they might occur. The standard math functions not listed in this table, such as fabs() , have no domain restrictions and cannot result in range or pole errors.
No asin(x) -1 Yes No atan(x) None Yes No
exp(x) , exp2(x) , expm1(x)
log(x) , log10(x) , log2(x)
x != 0 && !isinf(x) && !isnan(x)
scalbn(x, n) , scalbln(x, n)
x > 0 || (x == 0 && y > 0) ||
( x is an integer)
x != 0 && ! ( x is an integer)
fmod(x, y) , remainder(x, y) ,
remquo(x, y, quo)
nextafter(x, y) ,
nexttoward(x, y)
Domain and Pole Checking
The most reliable way to handle domain and pole errors is to prevent them by checking arguments beforehand, as in the following exemplar:
Range Checking
Programmers usually cannot prevent range errors, so the most reliable way to handle them is to detect when they have occurred and act accordingly.
The exact treatment of error conditions from math functions is tedious. The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines the following behavior for floating-point overflow:
A floating result overflows if the magnitude of the mathematical result is finite but so large that the mathematical result cannot be represented without extraordinary roundoff error in an object of the specified type. If a floating result overflows and default rounding is in effect, then the function returns the value of the macro HUGE_VAL , HUGE_VALF , or HUGE_VALL according to the return type, with the same sign as the correct value of the function; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value ERANGE ; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the «overflow» floating-point exception is raised.
It is preferable not to check for errors by comparing the returned value against HUGE_VAL or 0 for several reasons:
- These are, in general, valid (albeit unlikely) data values.
- Making such tests requires detailed knowledge of the various error returns for each math function.
- Multiple results aside from HUGE_VAL and 0 are possible, and programmers must know which are possible in each case.
- Different versions of the library have varied in their error-return behavior.
It can be unreliable to check for math errors using errno because an implementation might not set errno . For real functions, the programmer determines if the implementation sets errno by checking whether math_errhandling & MATH_ERRNO is nonzero. For complex functions, the C Standard, 7.3.2, paragraph 1, simply states that «an implementation may set errno but is not required to» [ISO/IEC 9899:2011].
The obsolete System V Interface Definition (SVID3) [UNIX 1992] provides more control over the treatment of errors in the math library. The programmer can define a function named matherr() that is invoked if errors occur in a math function. This function can print diagnostics, terminate the execution, or specify the desired return value. The matherr() function has not been adopted by C or POSIX, so it is not generally portable.
The following error-handing template uses C Standard functions for floating-point errors when the C macro math_errhandling is defined and indicates that they should be used; otherwise, it examines errno :
See FLP03-C. Detect and handle floating-point errors for more details on how to detect floating-point errors.
Subnormal Numbers
A subnormal number is a nonzero number that does not use all of its precision bits [ IEEE 754 2006 ]. These numbers can be used to represent values that are closer to 0 than the smallest normal number (one that uses all of its precision bits). However, the asin() , asinh() , atan() , atanh() , and erf() functions may produce range errors, specifically when passed a subnormal number. When evaluated with a subnormal number, these functions can produce an inexact, subnormal value, which is an underflow error. The C Standard, 7.12.1, paragraph 6 [ISO/IEC 9899:2011], defines the following behavior for floating-point underflow:
The result underflows if the magnitude of the mathematical result is so small that the mathematical result cannot be represented, without extraordinary roundoff error, in an object of the specified type. If the result underflows, the function returns an implementation-defined value whose magnitude is no greater than the smallest normalized positive number in the specified type; if the integer expression math_errhandling & MATH_ERRNO is nonzero, whether errno acquires the value ERANGE is implementation-defined; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, whether the ‘‘underflow’’ floating-point exception is raised is implementation-defined.
Implementations that support floating-point arithmetic but do not support subnormal numbers, such as IBM S/360 hex floating-point or nonconforming IEEE-754 implementations that skip subnormals (or support them by flushing them to zero), can return a range error when calling one of the following families of functions with the following arguments:
- fmod ((min+subnorm), min)
- remainder ((min+ subnorm ), min)
- remquo ((min+ subnorm ), min, quo)
where min is the minimum value for the corresponding floating point type and subnorm is a subnormal value.
If Annex F is supported and subnormal results are supported, the returned value is exact and a range error cannot occur. The C Standard, F.10.7.1 [ISO/IEC 9899:2011], specifies the following for the fmod() , remainder() , and remquo() functions:
When subnormal results are supported, the returned value is exact and is independent of the current rounding direction mode.
Annex F, subclause F.10.7.2, paragraph 2, and subclause F.10.7.3, paragraph 2, of the C Standard identify when subnormal results are supported.
Noncompliant Code Example ( sqrt() )
This noncompliant code example determines the square root of x :
However, this code may produce a domain error if x is negative.
Compliant Solution ( sqrt() )
Because this function has domain errors but no range errors, bounds checking can be used to prevent domain errors:
Noncompliant Code Example ( sinh() , Range Errors)
This noncompliant code example determines the hyperbolic sine of x :
This code may produce a range error if x has a very large magnitude.
Compliant Solution ( sinh() , Range Errors)
Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:
Noncompliant Code Example ( pow() )
This noncompliant code example raises x to the power of y :
This code may produce a domain error if x is negative and y is not an integer value or if x is 0 and y is 0. A domain error or pole error may occur if x is 0 and y is negative, and a range error may occur if the result cannot be represented as a double .
Compliant Solution ( pow() )
Because the pow() function can produce domain errors, pole errors, and range errors, the programmer must first check that x and y lie within the proper domain and do not generate a pole error and then detect whether a range error occurs and act accordingly:
Noncompliant Code Example ( asin() , Subnormal Number)
This noncompliant code example determines the inverse sine of x :
Compliant Solution ( asin() , Subnormal Number)
Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:
Risk Assessment
Failure to prevent or detect domain and range errors in math functions may cause unexpected results.
Источник
Table of Contents
- Introduction
- ⚠️What Is a Math Domain Error in Python?
- ➥ Fixing “ValueError: math domain error”-sqrt
- 💡 Solution 1: Using “cmath” Module
- 💡 Solution 2: Use Exception Handling
- ➥ “ValueError: math domain error” Examples
- ✰ Scenario 1: Math Domain Error While Using pow()
- ✰ Scenario 2: Python Math Domain Error While Using log()
- ✰ Scenario 3: Math Domain Error While Using asin()
- 📖 Exercise: Fixing Math Domain Error While Using Acos()
- Conclusion
Introduction
So, you sit down, grab a cup of coffee and start programming in Python. Then out of nowhere, this stupid python error shows up: ValueError: math domain error
. 😞
Sometimes it may seem annoying, but once you take time to understand what Math domain error
actually is, you will solve the problem without any hassle.
To fix this error, you must understand – what is meant by the domain of a function?
Let’s use an example to understand “the domain of a function.”
Given equation: y= √(x+4)
- y = dependent variable
- x = independent variable
The domain of the function above is x≥−4
. Here x can’t be less than −4 because other values won’t yield a real output.
❖ Thus, the domain of a function is a set of all possible values of the independent variable (‘x’) that yield a real/valid output for the dependent variable (‘y’).
If you have done something that is mathematically undefined (not possible mathematically), then Python throws ValueError: math domain error
.
➥ Fixing “ValueError: math domain error”-sqrt
Example:
from math import * print(sqrt(—5)) |
Output:
Traceback (most recent call last): File «D:/PycharmProjects/PythonErrors/Math Error.py», line 2, in <module> print(sqrt(—5)) ValueError: math domain error |
Explanation:
Calculating the square root of a negative number is outside the scope of Python, and it throws a ValueError
.
Now, let’s dive into the solutions to fix our problem!
💡 Solution 1: Using “cmath” Module
When you calculate the square root of a negative number in mathematics, you get an imaginary number. The module that allows Python to compute the square root of negative numbers and generate imaginary numbers as output is known as cmath
.
Solution:
from cmath import sqrt print(sqrt(—5)) |
Output:
2.23606797749979j
💡 Solution 2: Use Exception Handling
If you want to eliminate the error and you are not bothered about imaginary outputs, then you can use try-except
blocks. Thus, whenever Python comes across the ValueError: math domain error
it is handled by the except block.
Solution:
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!
Let us have a look at some other scenarios that lead to the occurrence of the math domain error
and the procedure to avoid this error.
➥ “ValueError: math domain error” Examples
✰ Scenario 1: Math Domain Error While Using pow()
Cause of Error: 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
.
Example:
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
Solution: Use the cmath
module to solve this problem.
- Note:
- Xy = ey ln x
Using the above property, the error can be avoided as follows:
from cmath import exp,log e = —1.7 print(exp(e * log(—3))) |
Output:
(0.0908055832509843+0.12498316306449488j)
✰ Scenario 2: Python Math Domain Error While Using log()
Consider the following example if you are working on Python 2.x:
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
Explanation: 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.
Solution:
To Avoid the error try this instead:
from __future__ import division
, which gives you Python 3 division behaviour in Python 2.7.
from __future__ import division import math print(2/3*math.log(2/3,2)) # Output: -0.389975000481 |
✰ Scenario 3: Math Domain Error While Using asin()
Example:
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
Explanation: math.asin()
method only accepts numbers between the range of -1 to 1. If you provide a number beyond of this range, it returns a ValueError – “ValueError: math domain error
“, and if you provide anything else other than a number, it returns error TypeError – “TypeError: a float is required
“.
Solution: You can avoid this error by passing a valid input number to the function that lies within the range of -1 and 1.
import math k = 0.25 print(«asin(«,k,«) is = «, math.asin(k)) #OUTPUT: asin( 0.25 ) is = 0.25268025514207865 |
📖 Exercise: Fixing Math Domain Error While Using Acos()
Note: When you pass a value to math.acos()
which does not lie within the range of -1 and 1, it raises a math domain error
.
Fix the following code:
import math print(math.acos(10)) |
Answer:
Conclusion
I hope this article helped you. Please subscribe and stay tuned for more exciting articles in the future. Happy learning! 📚
The domain of a mathematical function is the set of all possible input values. If you pass an undefined input to a function from the math library, you will raise the ValueError: math domain error.
To solve this error, ensure that you use a valid input for the mathematical function you wish to use. You can put a conditional statement in your code to check if the number is valid for the function before performing the calculation.
You cannot use functions from the math library with complex numbers, such as calculating a negative number’s square root. To do such calculations, use the cmath library.
This tutorial will go through the error in detail and solve it with the help of some code examples.
Table of contents
- ValueError: math domain error
- What is a ValueError?
- Example #1: Square Root of a Negative Number
- Solution #1: Use an if statement
- Solution #2: Use cmath
- Example #2: Logarithm of Zero
- Solution
- Summary
ValueError: math domain error
What is a ValueError?
In Python, a value is the information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.
The ValueError: math domain error occurs when you attempt to use a mathematical function with an invalid value. You will commonly see this error using the math.sqrt() and math.log() methods.
Example #1: Square Root of a Negative Number
Let’s look at an example of a program that calculates the square root of a number.
import math
number = int(input("Enter a number: "))
sqrt_number = math.sqrt(number)
print(f' The square root of {number} is {sqrt_number}')
We import the math library to use the square root function in the above code. We collect the number from the user using the input() function. Next, we find the square root of the number and print the result to the console using an f-string. Let’s run the code to see the result:
Enter a number: -4
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
3 number = int(input("Enter a number: "))
4
----> 5 sqrt_number = math.sqrt(number)
6
7 print(f' The square root of {number} is {sqrt_number}')
ValueError: math domain error
We raise the ValueError because a negative number does not have a real square root.
Solution #1: Use an if statement
To solve this error, we can check the value of the number before attempting to calculate the square root by using an if statement. Let’s look at the revised code:
import math
number = int(input("Enter a number: "))
if number > 0:
sqrt_number = math.sqrt(number)
print(f' The square root of {number} is {sqrt_number}')
else:
print('The number you input is less than zero. You cannot find the real square root of a negative number.')
In the above code, we check if the user’s number is greater than zero. If it is, we calculate the number’s square root and print it to the console. Otherwise, we print a statement telling the user the number is invalid for the square root function. Let’s run the code to see the result:
Enter a number: -4
The number you input is less than zero. You cannot find the real square root of a negative number.
Go to the article: Python Square Root Function for further reading on calculating the square root of a number in Python.
Solution #2: Use cmath
We can also solve the square root math domain error using the cmath library. This library provides access to mathematical functions for complex numbers. The square root of a negative number is a complex number with a real and an imaginary component. We will not raise a math domain error using the square root function from cmath on a negative number. Let’s look at the revised code:
import cmath
number = int(input("Enter a number: "))
sqrt_number = cmath.sqrt(number)
print(f' The square root of {number} is {sqrt_number}')
Let’s run the code to get the result:
Enter a number: -4
The square root of -4 is 2j
Example #2: Logarithm of Zero
Let’s look at an example of a program that calculates the natural logarithm of a number. The log() method returns the natural logarithm of a number or to a specified base. The syntax of the math.log() method is:
math.log(x, base)
Parameters:
- x: Required. The value to calculate the number logarithm for.
- base: Optional. The logarithmic base to use. The default is e.
import math
number = int(input("Enter a number: "))
print(f'The log of {number} is {math.log(number)}.')
We import the math library to use the natural logarithm function in the above code. We collect the number from the user using the input() function. Next, we find the natural logarithm of the number and print the result to the console using an f-string. Let’s run the code to see the result:
Enter a number: 0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
3 number = int(input("Enter a number: "))
4
----> 5 print(f'The log of {number} is {math.log(number)}.')
ValueError: math domain error
We raise the ValueError because you cannot calculate the natural logarithm of 0 or a negative number. The log(0) means that the exponent e raised to the power of a number is 0. An exponent can never result in 0, which means log(0) has no answer, resulting in the math domain error.
Solution
We can put an if statement in the code to check if the number we want to use is positive to solve this error. Let’s look at the revised code:
import math
number = int(input("Enter a number: "))
if number > 0:
print(f'The log of {number} is {math.log(number)}.')
else:
print(f'The number you provided is less than or equal to zero. You can only get the logarithm of positive real numbers')
Now we will only calculate the natural logarithm of the number if it is greater than zero. Let’s run the code to get the result:
Enter a number: 0
The number you provided is less than or equal to zero. You can only get the logarithm of positive real numbers
Summary
Congratulations on reading to the end of this tutorial! ValueError: math domain error occurs when you attempt to perform a mathematical function with an invalid number. Every mathematical function has a valid domain of input values you can choose. For example, the logarithmic function accepts all positive, real numbers. To solve this error, ensure you use input from the domain of a function. You can look up the function in the math library documentation to find what values are valid and which values will raise a ValueError.
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
You may encounter a special ValueError
when working with Python’s math
module.
ValueError: math domain error
Python raises this error when you try to do something that is not mathematically possible or mathematically defined.
To understand this error, have a look at the definition of the domain:
“The domain of a function is the complete set of possible values of the independent variable. Roughly speaking, the domain is the set of all possible (input) x-values which result in a valid (output) y-value.” (source)
The domain of a function is the set of all possible input values. If Python throws the ValueError: math domain error
, you’ve passed an undefined input into the math
function. Fix the error by passing a valid input for which the function is able to calculate a numerical output.
Here are a few examples:
The math domain error appears if you pass a negative argument into the math.sqrt()
function. It’s mathematically impossible to calculate the square root of a negative number without using complex numbers. Python doesn’t get that and throws a ValueError: math domain error
.
Here’s a minimal example:
from math import sqrt print(sqrt(-1)) ''' Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 2, in <module> print(sqrt(-1)) ValueError: math domain error '''
You can fix the math domain error by using the cmath
package that allows the creation of complex numbers:
from cmath import sqrt print(sqrt(-1)) # 1j
Python Math Domain Error Log
The math domain error
for the math.log()
function appears if you pass a zero value into it—the logarithm is not defined for value 0.
Here’s the code on an input value outside the domain of the logarithm function:
from math import log print(log(0))
The output is the math domain error:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in <module> print(log(0)) ValueError: math domain error
You can fix this error by passing a valid input value into the math.log()
function:
from math import log print(log(0.000001)) # -13.815510557964274
This error can sometimes appear if you pass a very small number into it—Python’s float type cannot express all numbers. To pass a value “close to 0”, use the Decimal
module with higher precision, or pass a very small input argument such as:
math.log(sys.float_info.min)
Python Math Domain Error Acos
The math domain error
for the math.acos()
function appears if you pass a value into it for which it is not defined—arccos is only defined for values between -1 and 1.
Here’s the wrong code:
import math print(math.acos(2))
The output is the math domain error:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in <module> print(math.acos(2)) ValueError: math domain error
You can fix this error by passing a valid input value between [-1,1] into the math.acos()
function:
import math print(math.acos(0.5)) # 1.0471975511965979
Python Math Domain Error Asin
The math domain error
for the math.asin()
function appears if you pass a value into it for which it is not defined—arcsin is only defined for values between -1 and 1.
Here’s the erroneous code:
import math print(math.asin(2))
The output is the math domain error:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in <module> print(math.asin(2)) ValueError: math domain error
You can fix this error by passing a valid input value between [-1,1] into the math.asin()
function:
import math print(math.asin(0.5)) # 0.5235987755982989
Python Math Domain Error Pow
The math domain error
for the math.pow(a,b)
function to calculate a**b appears if you pass a negative base value into it and try to calculate a negative power of it. The reason it is not defined is that any negative number to the power of 0.5 would be the square number—and thus, a complex number. But complex numbers are not defined by default in Python!
import math print(math.pow(-2, 0.5))
The output is the math domain error:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in <module> print(math.pow(-2, 0.5)) ValueError: math domain error
If you need a complex number, ab must be rewritten into eb ln a. For example:
import cmath print(cmath.exp(0.5 * cmath.log(-2))) # (8.659560562354932e-17+1.414213562373095j)
You see, it’s a complex number!
NumPy Math Domain Error — np.log(x)
import numpy as np import matplotlib.pyplot as plt # Plotting y = log(x) fig, ax = plt.subplots() ax.set(xlim=(-5, 20), ylim=(-4, 4), title='log(x)', ylabel='y', xlabel='x') x = np.linspace(-10, 20, num=1000) y = np.log(x) plt.plot(x, y)
This is the graph of log(x)
. Don’t worry if you don’t understand the code, what’s more important is the following point. You can see that log(x) tends to negative infinity as x tends to 0. Thus, it is mathematically meaningless to calculate the log of a negative number. If you try to do so, Python raises a math domain error.
>>> math.log(-10) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
In mathematics, there are operations which do not work on negative numbers or zero numbers. Consider the square root, for example. You cannot find the square root of a negative number. Python recognizes that not all operations work with negative or zero numbers.
Python will raise an error when you try to use a negative number on an operation that does not support one. In this guide, we’re going to talk about the cause of the ValueError: math domain error
. Toward the end of the guide, we’ll walk through a solution to this issue.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
ValueError: math domain error
The Python ValueError: math domain error
is raised when you use a number that is not supported by a mathematical operation. This error is commonly raised with the sqrt()
method and the log()
method.
The ValueError is a type of error that indicates you are performing a mathematical operation on a value that does not work with that operation. In the case of the “math domain error”, we are using a negative number or a zero number where we should not be.
Let’s walk through an example of the ValueError: math domain error
issue in action.
An Example Scenario
We are building a program that calculates the square root of a given number. This program is designed to help students revise their knowledge of square roots.
Let’s write a program that calculates the square root of a given number. We will start by importing the math library that we need to calculate a square root:
Next, we’re going to collect a number from the user:
number = input("Try solving the problem first using pencil and paper. Then, insert the number whose square root you want to verify: ")
We prompt the user to try finding the answer themselves, as our program is designed to help people check their answers. Next, we’re going to find the square root of the value the user inserts:
answer = math.sqrt(int(number))
We convert the value of “number”, which stores the number whose square root the user wants to find, into an integer. This is necessary because the input()
method, which we used to collect the aforementioned number, returns a string. We cannot find the square root of a string value.
Finally, let’s print the answer to the console:
print("The square root of {} is {}.".format(number, answer))
We use a format()
statement to add numbers to our string. Our string will show:
"The square root of [Number user inserted] is [The square root our program calculated]"
Let’s test our program with a negative number:
Try solving the problem first using pencil and paper. Then, insert the number whose square root you want to verify: -16 Traceback (most recent call last): File "test.py", line 5, in <module> answer = math.sqrt(int(number)) ValueError: math domain error
We inserted the value -16
into our program. Our code returned an error.
Let’s fix this error.
The Solution
To fix this error, we need to prompt the user that you cannot calculate the square root of a negative number before we execute the math.sqrt()
function.
Let’s revise our code to make this happen:
import math number = input("Try solving the problem first using pencil and paper. Then, insert the number whose square root you want to verify: ") if int(number) >= 0: answer = math.sqrt(int(number)) print("The square root of {} is {}.".format(number, answer)) else: print("You cannot find the square root of a number less than 0.")
We use an if
statement to check if the number the user inserts into the program is equal to or greater than zero. If the number meets this criterion, the contents of the if
statement run. Otherwise, the else
statement executes, presenting us with a message that we have inserted an invalid number.
Let’s run our program again. Our program returns:
Try solving the problem first using pencil and paper. Then, insert the number whose square root you want to verify: -16 You cannot find the square root of a number less than 0.
Our code works successfully.
Conclusion
The ValueError: math domain error
is raised when you perform a mathematical function on a negative or zero number which cannot be computed. To solve this error, make sure you are using a valid number for the mathematical function you are using.
If you want to learn more about coding in Python, check out our How to Learn Python guide. This guide contains a number of learning resources, courses, and books designed for people who are learning the Python programming language.
The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines three types of errors that relate specifically to math functions in <math.h>
. Paragraph 2 states
A domain error occurs if an input argument is outside the domain over which the mathematical function is defined.
Paragraph 3 states
A pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit.
Paragraph 4 states
A range error occurs if the mathematical result of the function cannot be represented in an object of the specified type, due to extreme magnitude.
An example of a domain error is the square root of a negative number, such as sqrt(-1.0)
, which has no meaning in real arithmetic. Contrastingly, 10 raised to the 1-millionth power, pow(10., 1e6)
, cannot be represented in many floating-point implementations because of the limited range of the type double
and consequently constitutes a range error. In both cases, the function will return some value, but the value returned is not the correct result of the computation. An example of a pole error is log(0.0)
, which results in negative infinity.
Programmers can prevent domain and pole errors by carefully bounds-checking the arguments before calling mathematical functions and taking alternative action if the bounds are violated.
Range errors usually cannot be prevented because they are dependent on the implementation of floating-point numbers as well as on the function being applied. Instead of preventing range errors, programmers should attempt to detect them and take alternative action if a range error occurs.
The following table lists the double
forms of standard mathematical functions, along with checks that should be performed to ensure a proper input domain, and indicates whether they can also result in range or pole errors, as reported by the C Standard. Both float
and long double
forms of these functions also exist but are omitted from the table for brevity. If a function has a specific domain over which it is defined, the programmer must check its input values. The programmer must also check for range errors where they might occur. The standard math functions not listed in this table, such as fabs()
, have no domain restrictions and cannot result in range or pole errors.
Function |
Domain |
Range |
Pole |
---|---|---|---|
|
|
No |
No |
asin(x) |
-1 <= x && x <= 1 |
Yes | No |
atan(x) |
None | Yes | No |
|
|
No |
No |
|
|
Yes |
No |
asinh(x) |
None | Yes | No |
|
|
Yes |
Yes |
|
None |
Yes |
No |
|
None |
Yes |
No |
|
None |
Yes |
No |
|
|
No |
Yes |
|
|
No |
Yes |
|
|
Yes |
No |
logb(x) |
x != 0 |
Yes | Yes |
|
None |
Yes |
No |
|
None |
Yes |
No |
|
|
Yes |
Yes |
|
|
No |
No |
erf(x) |
None | Yes | No |
|
None |
Yes |
No |
|
|
Yes |
Yes |
|
None |
Yes |
No |
|
|
Yes |
No |
|
None |
Yes |
No |
|
None |
Yes |
No |
|
None |
Yes |
No |
Domain and Pole Checking
The most reliable way to handle domain and pole errors is to prevent them by checking arguments beforehand, as in the following exemplar:
double safe_sqrt(double x) { if (x < 0) { fprintf(stderr, "sqrt requires a nonnegative argument"); /* Handle domain / pole error */ } return sqrt (x); }
Range Checking
Programmers usually cannot prevent range errors, so the most reliable way to handle them is to detect when they have occurred and act accordingly.
The exact treatment of error conditions from math functions is tedious. The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines the following behavior for floating-point overflow:
A floating result overflows if the magnitude of the mathematical result is finite but so large that the mathematical result cannot be represented without extraordinary roundoff error in an object of the specified type. If a floating result overflows and default rounding is in effect, then the function returns the value of the macro
HUGE_VAL
,HUGE_VALF
, orHUGE_VALL
according to the return type, with the same sign as the correct value of the function; if the integer expressionmath_errhandling & MATH_ERRNO
is nonzero, the integer expressionerrno
acquires the valueERANGE
; if the integer expressionmath_errhandling & MATH_ERREXCEPT
is nonzero, the «overflow» floating-point exception is raised.
It is preferable not to check for errors by comparing the returned value against HUGE_VAL
or 0
for several reasons:
- These are, in general, valid (albeit unlikely) data values.
- Making such tests requires detailed knowledge of the various error returns for each math function.
- Multiple results aside from
HUGE_VAL
and0
are possible, and programmers must know which are possible in each case. - Different versions of the library have varied in their error-return behavior.
It can be unreliable to check for math errors using errno
because an implementation might not set errno
. For real functions, the programmer determines if the implementation sets errno
by checking whether math_errhandling & MATH_ERRNO
is nonzero. For complex functions, the C Standard, 7.3.2, paragraph 1, simply states that «an implementation may set errno
but is not required to» [ISO/IEC 9899:2011].
The obsolete System V Interface Definition (SVID3) [UNIX 1992] provides more control over the treatment of errors in the math library. The programmer can define a function named matherr()
that is invoked if errors occur in a math function. This function can print diagnostics, terminate the execution, or specify the desired return value. The matherr()
function has not been adopted by C or POSIX, so it is not generally portable.
The following error-handing template uses C Standard functions for floating-point errors when the C macro math_errhandling
is defined and indicates that they should be used; otherwise, it examines errno
:
#include <math.h> #include <fenv.h> #include <errno.h> /* ... */ /* Use to call a math function and check errors */ { #pragma STDC FENV_ACCESS ON if (math_errhandling & MATH_ERREXCEPT) { feclearexcept(FE_ALL_EXCEPT); } errno = 0; /* Call the math function */ if ((math_errhandling & MATH_ERRNO) && errno != 0) { /* Handle range error */ } else if ((math_errhandling & MATH_ERREXCEPT) && fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) != 0) { /* Handle range error */ } }
See FLP03-C. Detect and handle floating-point errors for more details on how to detect floating-point errors.
Subnormal Numbers
A subnormal number is a nonzero number that does not use all of its precision bits [IEEE 754 2006]. These numbers can be used to represent values that are closer to 0 than the smallest normal number (one that uses all of its precision bits). However, the asin()
, asinh()
, atan()
, atanh()
, and erf()
functions may produce range errors, specifically when passed a subnormal number. When evaluated with a subnormal number, these functions can produce an inexact, subnormal value, which is an underflow error. The C Standard, 7.12.1, paragraph 6 [ISO/IEC 9899:2011], defines the following behavior for floating-point underflow:
The result underflows if the magnitude of the mathematical result is so small that the mathematical result cannot be represented, without extraordinary roundoff error, in an object of the specified type. If the result underflows, the function returns an implementation-defined value whose magnitude is no greater than the smallest normalized positive number in the specified type; if the integer expression
math_errhandling & MATH_ERRNO
is nonzero, whethererrno
acquires the valueERANGE
is implementation-defined; if the integer expressionmath_errhandling & MATH_ERREXCEPT
is nonzero, whether the ‘‘underflow’’ floating-point exception is raised is implementation-defined.
Implementations that support floating-point arithmetic but do not support subnormal numbers, such as IBM S/360 hex floating-point or nonconforming IEEE-754 implementations that skip subnormals (or support them by flushing them to zero), can return a range error when calling one of the following families of functions with the following arguments:
fmod
((min+subnorm), min)
remainder
((min+
), min)subnorm
remquo
((min+
), min, quo)subnorm
where min
is the minimum value for the corresponding floating point type and subnorm
is a subnormal value.
If Annex F is supported and subnormal results are supported, the returned value is exact and a range error cannot occur. The C Standard, F.10.7.1 [ISO/IEC 9899:2011], specifies the following for the fmod()
, remainder()
, and remquo()
functions:
When subnormal results are supported, the returned value is exact and is independent of the current rounding direction mode.
Annex F, subclause F.10.7.2, paragraph 2, and subclause F.10.7.3, paragraph 2, of the C Standard identify when subnormal results are supported.
Noncompliant Code Example (sqrt()
)
This noncompliant code example determines the square root of x
:
#include <math.h> void func(double x) { double result; result = sqrt(x); }
However, this code may produce a domain error if x
is negative.
Compliant Solution (sqrt()
)
Because this function has domain errors but no range errors, bounds checking can be used to prevent domain errors:
#include <math.h> void func(double x) { double result; if (isless(x, 0.0)) { /* Handle domain error */ } result = sqrt(x); }
Noncompliant Code Example (sinh()
, Range Errors)
This noncompliant code example determines the hyperbolic sine of x
:
#include <math.h> void func(double x) { double result; result = sinh(x); }
This code may produce a range error if x
has a very large magnitude.
Compliant Solution (sinh()
, Range Errors)
Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:
#include <math.h> #include <fenv.h> #include <errno.h> void func(double x) { double result; { #pragma STDC FENV_ACCESS ON if (math_errhandling & MATH_ERREXCEPT) { feclearexcept(FE_ALL_EXCEPT); } errno = 0; result = sinh(x); if ((math_errhandling & MATH_ERRNO) && errno != 0) { /* Handle range error */ } else if ((math_errhandling & MATH_ERREXCEPT) && fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) != 0) { /* Handle range error */ } } /* Use result... */ }
Noncompliant Code Example (pow()
)
This noncompliant code example raises x
to the power of y
:
#include <math.h> void func(double x, double y) { double result; result = pow(x, y); }
This code may produce a domain error if x
is negative and y
is not an integer value or if x
is 0 and y
is 0. A domain error or pole error may occur if x
is 0 and y
is negative, and a range error may occur if the result cannot be represented as a double
.
Compliant Solution (pow()
)
Because the pow()
function can produce domain errors, pole errors, and range errors, the programmer must first check that x
and y
lie within the proper domain and do not generate a pole error and then detect whether a range error occurs and act accordingly:
#include <math.h> #include <fenv.h> #include <errno.h> void func(double x, double y) { double result; if (((x == 0.0f) && islessequal(y, 0.0)) || isless(x, 0.0)) { /* Handle domain or pole error */ } { #pragma STDC FENV_ACCESS ON if (math_errhandling & MATH_ERREXCEPT) { feclearexcept(FE_ALL_EXCEPT); } errno = 0; result = pow(x, y); if ((math_errhandling & MATH_ERRNO) && errno != 0) { /* Handle range error */ } else if ((math_errhandling & MATH_ERREXCEPT) && fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) != 0) { /* Handle range error */ } } /* Use result... */ }
Noncompliant Code Example (asin()
, Subnormal Number)
This noncompliant code example determines the inverse sine of x
:
#include <math.h> void func(float x) { float result = asin(x); /* ... */ }
Compliant Solution (asin()
, Subnormal Number)
Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:
#include <math.h> #include <fenv.h> #include <errno.h> void func(float x) { float result; { #pragma STDC FENV_ACCESS ON if (math_errhandling & MATH_ERREXCEPT) { feclearexcept(FE_ALL_EXCEPT); } errno = 0; result = asin(x); if ((math_errhandling & MATH_ERRNO) && errno != 0) { /* Handle range error */ } else if ((math_errhandling & MATH_ERREXCEPT) && fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) != 0) { /* Handle range error */ } } /* Use result... */ }
Risk Assessment
Failure to prevent or detect domain and range errors in math functions may cause unexpected results.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
FLP32-C |
Medium |
Probable |
Medium |
P8 |
L2 |
Automated Detection
Tool |
Version |
Checker |
Description |
---|---|---|---|
Astrée |
22.04 |
stdlib-limits |
Partially checked |
Axivion Bauhaus Suite |
7.2.0 |
CertC-FLP32 | Partially implemented |
CodeSonar |
7.2p0 |
MATH.DOMAIN.ATAN MATH.DOMAIN.TOOHIGH MATH.DOMAIN.TOOLOW MATH.DOMAIN MATH.RANGE MATH.RANGE.GAMMA MATH.DOMAIN.LOG MATH.RANGE.LOG MATH.DOMAIN.FE_INVALID MATH.DOMAIN.POW MATH.RANGE.COSH.TOOHIGH MATH.RANGE.COSH.TOOLOW MATH.DOMAIN.SQRT |
Arctangent Domain Error Argument Too High Argument Too Low Floating Point Domain Error Floating Point Range Error Gamma on Zero Logarithm on Negative Value Logarithm on Zero Raises FE_INVALID Undefined Power of Zero cosh on High Number cosh on Low Number sqrt on Negative Value |
Helix QAC |
2022.4 |
C5025 C++5033 |
|
Parasoft C/C++test |
2022.2 |
CERT_C-FLP32-a |
Validate values passed to library functions |
PC-lint Plus |
1.4 |
2423 |
Partially supported: reports domain errors for functions with the Semantics *dom_1, *dom_lt0, or *dom_lt1, including standard library math functions |
Polyspace Bug Finder |
R2022b |
CERT-C: Rule FLP32-C | Checks for invalid use of standard library floating point routine (rule fully covered) |
PRQA QA-C |
9.7 |
5025 | |
PRQA QA-C++ |
4.4 |
5033 | |
RuleChecker |
22.04 |
stdlib-limits |
Partially checked |
TrustInSoft Analyzer |
1.38 |
out-of-range argument | Partially verified. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Key here (explains table format and definitions)
CERT-CWE Mapping Notes
Key here for mapping notes
CWE-391 and FLP32-C
Intersection( CWE-391, FLP32-C) =
- Failure to detect range errors in floating-point calculations
CWE-391 — FLP32-C
- Failure to detect errors in functions besides floating-point calculations
FLP32-C – CWE-391 =
- Failure to detect domain errors in floating-point calculations
CWE-682 and FLP32-C
Independent( INT34-C, FLP32-C, INT33-C) CWE-682 = Union( FLP32-C, list) where list =
- Incorrect calculations that do not involve floating-point range errors
Bibliography
Автор оригинала: Chris.
Вы можете столкнуться с специальными ValueError
При работе с Python’s Математический модуль Отказ
ValueError: math domain error
Python поднимает эту ошибку, когда вы пытаетесь сделать то, что не математически возможно или математически определяется.
Чтобы понять эту ошибку, посмотрите на определение домен :
« Домен функции – это полный набор возможных значений независимой переменной. Грубо говоря, домен это набор всех возможных (входных) X-значений, который приводит к действительному (выводу) Y-значению. ” ( Источник )
Домен функции – это набор всех возможных входных значений. Если Python бросает ValueError: Ошибка математического домена
Вы пропустили неопределенный ввод в Математика
функция. Исправьте ошибку, передавая действительный вход, для которого функция может рассчитать числовой выход.
Вот несколько примеров:
Ошибка домена математики Python SQRT
Ошибка по математике домена появляется, если вы передаете отрицательный аргумент в math.sqrt ()
функция. Математически невозможно рассчитать квадратный корень отрицательного числа без использования сложных чисел. Python не получает это и бросает ValueError: Ошибка математического домена
Отказ
Вот минимальный пример:
from math import sqrt print(sqrt(-1)) ''' Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 2, in print(sqrt(-1)) ValueError: math domain error '''
Вы можете исправить ошибку математической домена, используя CMATH
Пакет, который позволяет создавать комплексные числа:
from cmath import sqrt print(sqrt(-1)) # 1j
Журнал ошибки домена Python Math
Ошибка математической домена
для math.log ()
Появится функция, если вы проходите нулевое значение в него – логарифм не определен для значения 0.
Вот код на входном значении за пределами домена функции логарифма:
from math import log print(log(0))
Выходной выход – это ошибка домена математики:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in print(log(0)) ValueError: math domain error
Вы можете исправить эту ошибку, передавая действительное входное значение в math.log ()
Функция:
from math import log print(log(0.000001)) # -13.815510557964274
Эта ошибка иногда может появиться, если вы пройдете очень небольшое число в IT-Python, который не может выразить все номера. Чтобы пройти значение «Близки к 0», используйте Десятичная
Модуль с более высокой точностью или пройти очень маленький входной аргумент, такой как:
math.log(sys.float_info.min)
Ошибка ошибки домена математики Python ACOS
Ошибка математической домена
для math.acos ()
Появится функция, если вы передаете значение для него, для которого он не определен-ARCCO, определяется только значениями между -1 и 1.
Вот неверный код:
import math print(math.acos(2))
Выходной выход – это ошибка домена математики:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in print(math.acos(2)) ValueError: math domain error
Вы можете исправить эту ошибку, передавая действительное входное значение между [-1,1] в math.acos ()
Функция:
import math print(math.acos(0.5)) # 1.0471975511965979
Ошибка домена Math Python Asin
Ошибка математической домена
для math.asin ()
Функция появляется, если вы передаете значение в него, для которого он не определен – Arcsin определяется только значениями между -1 и 1.
Вот ошибочный код:
import math print(math.asin(2))
Выходной выход – это ошибка домена математики:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in print(math.asin(2)) ValueError: math domain error
Вы можете исправить эту ошибку, передавая действительное входное значение между [-1,1] в math.asin ()
Функция:
import math print(math.asin(0.5)) # 0.5235987755982989
Ошибка ошибки домена Python Math POW POW
Ошибка математической домена
для math.pow (a, b)
Функция для расчета A ** B, по-видимому, если вы передаете негативное базовое значение, и попытайтесь вычислить негативную мощность. Причина этого не определена, состоит в том, что любое отрицательное число к мощности 0,5 будет квадратным числом – и, таким образом, комплексное число. Но комплексные числа не определены по умолчанию в Python!
import math print(math.pow(-2, 0.5))
Выходной выход – это ошибка домена математики:
Traceback (most recent call last): File "C:UsersxcentDesktopFinxterBlogcode.py", line 3, in print(math.pow(-2, 0.5)) ValueError: math domain error
Если вам нужен комплекс номер, A B должен быть переписан в E B ln a Отказ Например:
import cmath print(cmath.exp(0.5 * cmath.log(-2))) # (8.659560562354932e-17+1.414213562373095j)
Видите ли, это сложный номер!
Ошибка numpy математический домен – np.log (x)
import numpy as np import matplotlib.pyplot as plt # Plotting y = log(x) fig, ax = plt.subplots() ax.set(xlim=(-5, 20), ylim=(-4, 4), title='log(x)', ylabel='y', xlabel='x') x = np.linspace(-10, 20, num=1000) y = np.log(x) plt.plot(x, y)
Это график log (x)
. Не волнуйтесь, если вы не понимаете код, что важнее, является следующим точком. Вы можете видеть, что журнал (X) имеет тенденцию к отрицательной бесконечности, когда X имеет тенденцию к 0. Таким образом, математически бессмысленно рассчитать журнал отрицательного числа. Если вы попытаетесь сделать это, Python поднимает ошибку математической домена.
>>> math.log(-10) Traceback (most recent call last): File "", line 1, in ValueError: math domain error
Куда пойти отсюда?
Достаточно теории, давайте познакомимся!
Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?
Практические проекты – это то, как вы обостряете вашу пилу в кодировке!
Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?
Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.
Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.
Присоединяйтесь к свободному вебинару сейчас!
Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.
Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.
Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.
Оригинал: “https://blog.finxter.com/python-math-domain-error/”
ValueError: math domain error
While working with mathematical functions in Python, you might come across an error called «ValueError math domain error«. This error is usually encountered when you are trying to solve quadratic equations or finding out the square root of a negative number.
You can avoid this error by providing the correct values to the math functions. Avoiding the use of negative values will be ideal.
Let us look at some examples where the error might be encountered.
Example 1: Square Root of Negative Number
We can calculate the square root of a number in python by importing the sqrt method from the math module. But what if a user entered a negative number?
Will it throw an error or will we get the desired output? let’s understand it with a few examples.
from math import sqrt
# Initialising the variable 'num'
num=float(input("Enter number :"))
#Square root of num
print("Square root of given number :",sqrt(num))
Output:
Enter number :12
Square root of given number : 3.4641016151377544
Enter number :-12
File "sqr.py", line 5, in <module>
print("Square root of given number :",sqrt(num))
ValueError: math domain error
If num less then 0 or negative number then this code throws a math domain error as mentioned above.
Solution:
We can either handle the ValueError by raising an exception or by importing sqrt method from cmath library lets discuss both of them.
Method 1: Using Try and Except Block for Handling the Error.
from math import sqrt
#try block for code to be tested
try:
#intialising the variable 'num'
num=float(input("Enter Number :"))
#Square root
print("Square root of given number :",sqrt(num))
#except block if error is raised
except ValueError:
print("Please enter a number greater than zero ")
OUTPUT :
Enter Number : 12
Square root of given number : 3.4641016151377544
Enter Number : -12
Please enter a number greater than zero
In the above code, when we enter a positive value we will get the desired output. But, when we will enter a negative value it’ll throw an error i.e «ValueError: math domain error«.
And to handle the ValueError we use try and except block.
The try block includes the code to be tested.
The Except block handles the error by displaying the desired message. Which in this case is «Please enter the number greater than zero«.
Method2: Importing Sqrt From «cmath» Which Will Return Square Root of Negative Number in Complex/Imaginary Form.
# Importing cmath module
from cmath import sqrt
# Input from user
num=float(input("Enter Number: "))
#Square root
print("Square root of given number : ", sqrt(num))
OUTPUT:
Enter Number : 12
Square root of given number : (3.4641016151377544+0j)
Enter Number : -12
Square root of given number : 3.4641016151377544j
In Method 1 we did not get the result instead we raised an exception. But what if we want the square root of a negative index in complex form.
To solve this issue import «sqrt» from cmath module. Which shows the result in complex/imaginary form as in mathematics.
When we import the cmath module the result which we will get will be in the complex form as shown in the output of «Method 2«.
Example 2: Log of a Negative Number
#importing log from math module
from math import log
#Intialising the variable 'num'
num= float(input("Enter Number :"))
#Natural logarithm of num
print("Natural logarithm of provided number :",log(num))
OUTPUT:
Enter Number :12
Natural logarithm of provided number : 2.4849066497880004
Enter Number :-12
File "sqr.py", line 6, in <module>
print("Natural logarithm of provided number :",log(num))
ValueError: math domain error
In the above code, When we try to find the log of the positive value we get the desired output. But when we try to find the log of the negative index it throws an error «ValueError: math domain error«.
This is because the negative of the log is not defined in python.