What is ValueError: math domain error and how to fix it

Python will raise a ValueError when an operation or function receives an argument that has the right type but an inappropriate value.

When using the math module, you get a "ValueError: math domain error" when you are making use of a math function with an argument value that is outside the valid domain for that function.

To put it in simple words, mathematics has some rules, if you do not follow then if you do not follow then it's considered to be an invalid question.


Examples: ValueError: math domain error

    1. Trying to get the square root of a negative number

    import math
    
    print(math.sqrt(-1))
    Output:
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 3, in <module>
        print(math.sqrt(-1))
              ^^^^^^^^^^^^^
    
    ValueError: math domain error

    2. Trying to get the log of negative numbers

    import math
    
    print(math.log(-10))
    Output:
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 3, in &yl;module>
        print(math.log(-10))
              ^^^^^^^^^^^^^
    
    ValueError: math domain error

    3. Trying to get arc sine of a value greater than 1

    import math
    
    print(math.asin(1.5))
    Output:
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 3, in &yl;module>
        print(math.asin(2.1)))
              ^^^^^^^^^^^^^
    
    ValueError: math domain error

    4. Trying to get hyperbolic cosine of a large positive number

    import math
    
    print(math.cosh(5100))
    Output:
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 3, in &yl;module>
        print(math.cosh(5100)))
              ^^^^^^^^^^^^^
    
    ValueError: math domain error

    Comments & Discussion

    Facing issues? Have questions? Post them here! We're happy to help!