Traceback (Most recent call last) Math Domain error

Asked

Viewed 85 times

0

import math

a = float(input("Digite 'a': "))
b = float(input("Digite 'b': "))
c = float(input("Digite 'c': "))

delta = b**2 - (4*a*c)

if(delta < 0):
  print("Raízes complexas!")
elif(delta == 0):
  print("2 raízes reais iguais!")
else:
  print("2 raízes reais diferentes!")

x1 = (-b + math.sqrt(delta))/2*a
x2 = (-b - math.sqrt(delta))/2*a

print("As raízes são:", x1, " e ", x2)

Digite 'a': 1
Digite 'b': 1
Digite 'c': 1
Raízes complexas!
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-51bd2b58d810> in <module>()
     14   print("2 raízes reais diferentes!")
     15 
---> 16 x1 = (-b + math.sqrt(delta))/2*a
     17 x2 = (-b - math.sqrt(delta))/2*a
     18 

ValueError: math domain error
  • But if it has complex roots why you try to calculate them as if they were real?

  • In reality the roots are: (-0.500000 - 0.866025i) and (-0.500000 + 0.866025i), where i is the square root of (-1).

  • What I’m trying to understand is what are the factors that caused the 'Valueerror', what is wrong about programming, not mathematics.

  • Without seeing the code is hard to guess (it would be nice to [Edit] the question and add it), but assuming that the delta has been calculated correctly, so it is negative and math.sqrt spear one ValueError when the number is negative. In this case you should use the cmath module: https://docs.python.org/3/library/cmath.html#module-cmath - And not to be boring, but be aware that the error is related to programming and also to mathematics :-)

  • 2

    Well, either you use the module cmath, that can work with complex numbers (including square root of negative numbers), or only calculate the delta root if the delta is positive, as was done for example here: https://answall.com/a/437857/112052

  • Sorry ignorance, I am extremely 'Noob' in programming. How I use cmath?

  • 1

    The same way you used Math: import cmath and then cmath.sqrt (basically, where there is "Math", change to "cmath")

  • And where is math.sqrt(delta) use cmath.sqrt(delta)

  • That’s exactly what I figured, thank you very much.

Show 4 more comments

1 answer

0

The error happens because your program tries to get the square root of a negative number, which is not allowed by the function Math.sqrt. To get the complex values you will have to use the library cmath:

import cmath

a = float(input("Digite 'a': "))
b = float(input("Digite 'b': "))
c = float(input("Digite 'c': "))

delta = b**2 - (4*a*c)

if(delta < 0):
  print("Raízes complexas!")
elif(delta == 0):
  print("2 raízes reais iguais!")
else:
  print("2 raízes reais diferentes!")

x1 = (-b + cmath.sqrt(delta))/2*a
x2 = (-b - cmath.sqrt(delta))/2*a

print("As raízes são:", x1, " e ", x2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.