-1

Can someone tell me why am I getting this error?

Traceback (most recent call last):
  File "file.py", line 14, in <module>
    p2 = math.sqrt(b*b -4*a*c)
ValueError: math domain error

I'm a newbie coding, so need some help :)

My code looks like this:

# -*- coding: utf-8 -*-
a = input("¿Qué valor es a?")
while(str(a).isdigit() != True):
  a = input("Porfavor, introduce un número para a, no un texto")
b = input("¿Qué valor es b?")
while(str(b).isdigit() != True):
  b = input("Porfavor, introduce un número para b, no un texto")
c = input("¿Qué valor es c?")
while(str(c).isdigit() != True):
  c = input("Porfavor, introduce un número para c, no un texto")

import math
p1 = b * -1
p2 = math.sqrt(b*b -4*a*c)
p3 = 2*a
s1 = (p1+p2)/p3
s2 = (p1-p2)/p3
print("Soluciones :", s1, " y ", s2)
  • 2
    `math.sqrt` doesn't handle negative values... – juanpa.arrivillaga Apr 13 '17 at 22:32
  • Are you sure the parameters a,b, and c you entered when executing were ones with a valid solution? If `4*a*c > b*b` there's no solution to the quadratic equation. You should add a check of `IF(4*a*c>b*b): print("No solutions") else: ...` – trashy Apr 13 '17 at 22:33
  • @trashy sure there is a solution, if your domain is the complex numbers. – juanpa.arrivillaga Apr 13 '17 at 22:36
  • @juanpa.arrivillaga There was no mention of using complex numbers in this entire post. Of course you can use cmath for the complex sqrt functions and then find the two imaginary roots. But I don't think that was what the question was about. (Or use the negative value for the normal sqrt and add the i and -i by hand) – trashy Apr 13 '17 at 22:39
  • @trashy my only point is that the question needs to be better specified. – juanpa.arrivillaga Apr 13 '17 at 22:41

2 Answers2

0

You have to make it so that math.sqrt doesn't take in negative values. So if b*b-4*a*c is a negative number, then you will get the math domain error. A way to solve this is to check beforehand if the value that's going in the sqrt operation is going to be a negative value with an if statement.

vbhaip
  • 716
  • 8
  • 6
0

I'm assuming you aren't looking to find imaginary roots if you were you should look at cmath

You should change that block to

try:
    p1 = b * -1
    math.sqrt(b**2 - 4*a*c)
    p3 = 2*a
    s1 = (p1+p2)/p3
    s2 = (p1-p2)/p3
    print("Soluciones :", s1, " y ", s2)
except ValueError:
    print("No real solution")

This is called exception handling, and it's the perfect tool for situations like this. The only time that it will go to the except statement is if a math.sqrt() is given a negative. And in that case the roots are imaginary so print("No real Solution") or whatever error message you want!

Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27