Python Value Error :Math Domain Error in Python - GeeksforGeeks (2024)

Last Updated : 02 Oct, 2023

Summarize

Comments

Improve

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

Output 1:

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

Output 2:

Enter the number: -5The 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: 4The log of 4 is 1.3862943611198906

Output 2:

Enter the number: -5Cannot 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: 1The arc cosine of 1 is 0.0

Output 2

Enter the number: -3Cannot 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.



S

sameekshamedewar

Python Value Error :Math Domain Error in Python - GeeksforGeeks (1)

Improve

Next Article

Python | Decimal to_integral_value() method

Please Login to comment...

Python Value Error :Math Domain Error in Python - GeeksforGeeks (2024)
Top Articles
SAS Article: Beefutures - Decoding the Waggle Dance
How Prepaid Funerals Work (Funeral Director Tells The Truth)
jazmen00 x & jazmen00 mega| Discover
Craigslist Vans
Shorthand: The Write Way to Speed Up Communication
5 Bijwerkingen van zwemmen in een zwembad met te veel chloor - Bereik uw gezondheidsdoelen met praktische hulpmiddelen voor eten en fitness, deskundige bronnen en een betrokken gemeenschap.
Nc Maxpreps
Mustangps.instructure
Yi Asian Chinese Union
Culver's Flavor Of The Day Monroe
A.e.a.o.n.m.s
Hallelu-JaH - Psalm 119 - inleiding
Whitley County Ky Mugshots Busted
C-Date im Test 2023 – Kosten, Erfahrungen & Funktionsweise
Sport-News heute – Schweiz & International | aktuell im Ticker
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Dtab Customs
How Much Is Tay Ks Bail
Walgreens San Pedro And Hildebrand
50 Shades Of Grey Movie 123Movies
Aaa Saugus Ma Appointment
Uta Kinesiology Advising
Long Island Jobs Craigslist
Accident On 215
Viha Email Login
Tyrone Unblocked Games Bitlife
Conan Exiles Sorcery Guide – How To Learn, Cast & Unlock Spells
Like Some Annoyed Drivers Wsj Crossword
Does Hunter Schafer Have A Dick
Sessional Dates U Of T
Dexter Gomovies
John Deere 44 Snowblower Parts Manual
Revelry Room Seattle
Datingscout Wantmatures
Workday Latech Edu
3302577704
Ludvigsen Mortuary Fremont Nebraska
Is Arnold Swansinger Married
Dollar Tree's 1,000 store closure tells the perils of poor acquisitions
What Is Kik and Why Do Teenagers Love It?
Umiami Sorority Rankings
sacramento for sale by owner "boats" - craigslist
Lovely Nails Prices (2024) – Salon Rates
Chubbs Canton Il
Willkommen an der Uni Würzburg | WueStart
Zeeks Pizza Calories
Haunted Mansion Showtimes Near Millstone 14
Best Restaurant In Glendale Az
Automatic Vehicle Accident Detection and Messageing System – IJERT
ESPN's New Standalone Streaming Service Will Be Available Through Disney+ In 2025
Ark Silica Pearls Gfi
Tamilblasters.wu
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5931

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.