Math Domain Error Quadratic Formula - python

Figured out the errors except for this last one, Im now getting this error message, and can't figure out why, I'm using the exact formulas for x1 and x2 that my teacher gave us to use and i'm not able to figure the error out.
# Quadratic Formula
# Import the math library to use sqrt() function to find the square root
import math
print("This equation solves for x in the binomial equation: ax^2 + bx + c = 0")
# Get the equation's coefficients and constant from the user
a = 0
while a == 0:
try:
a = float(input("Enter the first coefficeint, or a, value: "))
if a == 0:
raise ValueError
except ValueError:
print("The value you entered is invalid. Zero is not allowed")
else:
break
while (True):
try:
b = float(input("Enter the Second coefficeint, or b, value: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
while (True):
try:
c = float(input("Enter the last coefficeint, or c, value: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
d = (b**2) - (4*a*c)
x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a)
x2 = ((-b) - math.sqrt(b**2 - 4*a*c)) / (2*a)
print("X is: ", x1, " or ", x2)
do_calculation = True
while(do_calculation):
another_calculation = input("Do you want to perform another calculation? (y/n):")
if(another_calculation !="y"):
This equation solves for x in the binomial equation: ax^2 + bx + c = 0
Enter the first coefficeint, or a, value: 2
Enter the Second coefficeint, or b, value: 3
Enter the last coefficeint, or c, value: 4
Traceback (most recent call last):
File "/Users/cadenhastie/Downloads/Jtwyp6QuadraticEqnCalc/improvedquadraticeqncalc.py", line 34, in
x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a)
ValueError: math domain error

You have try statements with no corresponding except statement. You should generally avoid while True:. The indentation in your code has many issues
To get one value from the user with error handling, you could do something like the code below. You would then repeat this for each coefficient you want the user to enter. You probably want to wrap this in a function at some point so you are not writing duplicate code.
a = 0
while a == 0:
try:
a = float(input("Enter the first coefficeint, or a, value: "))
if a == 0:
raise ValueError
except ValueError:
print("The value you entered is invalid. Zero is not allowed")

Related

This Python code for quadratic equation isn't working

I'm trying to get the userinput for a,b,c using a function and it doesn't seems to work
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
print("The equation root of the numbers is" quadratic)
equationroots()
You have not used the proper intents, This is what your code supposed to be.
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
quadratic = equationroots()
print("The equation root of the numbers is", quadratic)
Indentation is very important in Python to separate block statements. It appears your indentation is off, leading to some lines not being executed when you intend.
For example, the variables my, sqrt_val, and quadratic are only calculated if the except label is reached. This means they are only attempted to be calculated if there is an input error, which wouldn't work anyways.
It's possible you also pasted in your code and the formatting was adjusted, and that isn't the issue. If that is the case, please edit the question to reflect the formatting and indentation you are using.
You need to fix your indentations from the except portion. Indentations are very important in python
fix this portion:
except ValueError:
print("Not a number!")
my = (b*b)-(4*a*c)
sqrt_val = math.sqrt(abs(my))
quadratic = ((-b)+sqrt_val)/(2*a)
return quadratic
then call your function first then use that to print your statement. Like,
quadratic = equationroots()
print(f"The equation root of the numbers is {quadratic}")

PYTHON ValueError - how i can change my code so it would bring exception?

As in the topic. While i give non number value it would not bring up exception but rise error in console. How can i improve my code so it would work as it is intended?
def div():
given = False
while not given:
a = int(input("Input first number: "))
b = int(input("Input second number: "))
try:
c = (a / b)
except ValueError:
print('Value Error - provide two numbers')
continue
except ZeroDivisionError:
print('Zero Division Error')
continue
return f'a/b = {c}'
print(div())
Use something like this:
Add you inputs also in the try block and add a except block for that.
def div():
given = False
while not given:
try:
a = int(input("Input first number: "))
b = int(input("Input second number: "))
c = (a / b)
except ValueError:
print('Value Error - provide two numbers')
continue
except ZeroDivisionError:
print('Zero Division Error')
continue
return f'a/b = {c}'
print(div())
The problem is that the string needs to be numeric. So, you need to assert if the input of the user is numeric before applying int(). So, I would just add the int() inside the try and it will catch it
def div():
given = False
while not given:
a = input("Input first number: ")
b = input("Input second number: ")
try:
c = (int(a) / int(b))
except ValueError:
print('Value Error - provide two numbers')
continue
except ZeroDivisionError:
print('Zero Division Error')
continue
return f'a/b = {c}'
print(div())
This is because you are converting the input to an integer outside of the try block.
Try (pun intended) moving it into the the try block:
def div():
given = False
while not given:
try:
a = int(input("Input first number: "))
b = int(input("Input second number: "))
c = (a / b)
except ValueError:
print('Value Error - provide a number')
continue
except ZeroDivisionError:
print('Zero Division Error')
continue
return f'a/b = {c}'
print(div())
You need to rearrange your code and put the inputs in the try/except blocks. Additionally, you could simply use while True:
def div():
while True:
try:
a = int(input("Input first number: "))
b = int(input("Input second number: "))
c = (a / b)
except ValueError:
print('Value Error - provide two numbers')
continue
except ZeroDivisionError:
print('Zero Division Error')
continue
return f'a/b = {c}'
print(div())

Python - Problems with a while loop

For my program I must enter a positive number, but if I enter a negative number I need the program to error with a message saying, "Please use a positive number and try again", then go back to the part where you input a number. It's stuck in a loop. Here's my code:
import math
# Receive the input number from the user
x = float(input("Enter a positive number: "))
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
#Perform the successive approximations
while True:
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
if diference <= tolerance:
break
elif x < 0:
print("Please enter a positive number")
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate: ", math.sqrt(x))
You can fix it by put your input() into while loop
import math
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
while True:
# Receive the input number from the user
x = float(input("Enter a positive number: "))
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
if diference <= tolerance:
break
elif x < 0:
print("Please enter a positive number")
--snip--
The issue is that you need to re-request the user input inside of the while loop as others have already mentioned.
A more thorough version of this answer would also be to refactor the order of operations inside of the while loop. In the code you are running the math operations on x before you validate that it is greater than zero. If the math is known to fail without a positive integer you would have a bug in your code that could lead to an unhandled exception. Here is another version with switches the if statement so we check the input before doing anything else - which makes the program less likely to throw an exception based on the input.
import math
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
#Perform the successive approximations
while True:
# Receive the input number from the user
x = float(input("Please enter a positive number:"))
if x <= tolerance:
print("Invalid input.")
continue
else:
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
break
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate: ", math.sqrt(x))
elif x < 0:
print("Please enter a positive number")
# Receive the input number from the user
x = float(input("Enter a positive number: "))
add the 4th line in your code. it will work. you were not receiving the input again after the fail attempt.

python linear equation with Cramer's rule

I'm new to python and attempting to write a linear equation using Cramer's Rule. I've entered the formula and have code prompting user to enter a,b,c,d,e and f but my code is getting a syntax error. I'd like to fix the code and also have a system for researching and correcting future errors.
a,b,c,d,e,f = float(input("Enter amount: ")
a*x + by = e
cx + dy = f
x = ed-bf/ad-bc
y=af-ed/ad-bc
if (ad - bc == 0)print("The equation has no solution")
else print ("x=" x, "y=" y,)
Basically, your code was one giant syntax error. Please read some basic tutorial, as was suggested in the comments. Hopefully this will help in the learning process (I didn't go through the actual math formulas):
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = float(input("Enter d: "))
e = float(input("Enter e: "))
f = float(input("Enter f: "))
##a*x + by = e
##cx + dy = f
if (a*d - b*c == 0):
print("The equation has no solution")
else:
x = (e*d-b*f)/(a*d-b*c)
y = (a*f-e*d)/(a*d-b*c)
print ("x=%s" % x, "y=%s" % y)
You have to put * between the numbers you want to multiply. You had one parenthesis missing from your input statement. The equations themselves are commented out, because otherwise Python takes them as a code (incorrectly written one). You have to enclose the denominator in parentheses because math. You have to end the if, else, elif, for, while and such with :. Indentation is VERY important in Python.

Python - No valuerror on int with isalpha

Why is no ValueError raised on this try / except when isalpha should fail.
I know that isalpha returns false if given a number
In [9]: ans = input("Enter a Letter")
Enter a Letter4
In [10]: ans.isalpha()
Out[10]: False
How do I get the value error if they supply a number instead of a y or n? Because if the try is false shouldn't it stop being true and not print my trajectory?
import sys
v0 = float(input("What velocity would you like? "))
g = float(input("What gravity would you like? "))
t = float(input("What time decimal would you like? "))
print("""
We have the following inputs.
v0 is %d
g is %d
t is %d
Is this correct? [Y/n]
""" % (v0, g, t))
while True:
try:
answer = input("\t >> ").isalpha()
print(v0 * t - 0.5 * g * t ** 2)
except ValueError as err:
print("Not a valid entry", err.answer)
sys.exit()
finally:
print("would you like another?")
break
For example if the user types 5 not a y or n still gets an answer
$ python3 ball.py
What velocity would you like? 2
What gravity would you like? 3
What time decimal would you like? 4
We have the following inputs.
v0 is 2
g is 3
t is 4
Is this correct? [Y/n]
>> 5
-16.0
would you like another?
except ValueError as err: only happens when there is a ValueError thrown. The value of answer is False, but that is just an arbitrary boolean value, not an error.
See ValueError documentation for examples of things that are errors.
In your case, simply test:
answer = input("\t >> ")
if answer.isalpha():
print(v0 * t - 0.5 * g * t ** 2)
break
In general you should prefer to use normal control flow logic to handle a range of user input rather than raising/catching exceptions.
You need to raise the error yourself. There is no exception raised by typing in something that you don't prefer:
try:
answer = input("\t >> ").isalpha()
if not answer:
raise ValueError
print(v0 * t - 0.5 * g * t ** 2)
except ValueError as err:
print("Not a valid entry", err.answer)
sys.exit()
Posting an answer for clarity trying to provide a way to be more consistent and explicit with the treatment of strings and int's. By using isinstance I declare to a person reading my code explicitly what my values are to be hopefully improving readability.
answer = input("\t >> ")
if isinstance(int(answer), int) is True:
raise ValueError("Ints aren't valid input")
sys.exit()
elif isinstance(answer, str) is True:
print(v0 * t - 0.5 * g * t ** 2)
else:
print("Ok please ammend your entries")
Should I have differing requirements later this could easily be abstracted into a function, which because isinstance allows checking against multiple types increases flexibility.
Reference How to properly use python's isinstance() to check if a variable is a number?
def testSomething(arg1, **types):
if isintance(arg1, [types]):
do_something

Categories

Resources