4

I'm very new to python programming and to this site. I'm currently working on a problem and can't seem to understand the error.

import math
# Problem number 5.
A5 = 5
B5 = 0
C5 = 6.5
# Root1
x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Root2
x10 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Print solution
print()
print('Problem #5')
print('Root 1: ',x9)
print('Root 2: ',x10)

I get this after i run it:

    x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
ValueError: math domain error

I did the problem on paper and got an answer for both...

  • 2
    How did you get the square root of 0^2 - 4*5*6.5 = -130 on paper? Because that's what's happening here, i.e., that's the `math domain error`. –  Jan 30 '15 at 09:25
  • possible duplicate of [ValueError: math domain error](http://stackoverflow.com/questions/15890503/valueerror-math-domain-error) – user Jan 30 '15 at 10:05
  • Well, i used a calculator and only sqrt the -4(5)(6.5) and got 11.40 and then divided that by 10 and got 1.14 as the answer. – EggRolls4Me Jan 31 '15 at 00:39

1 Answers1

3

If you got an answer, it must have been a complex number (which are not included by default in Python). Look at the line math.sqrt(B5**2 - 4*A5*C5).

This evaluates as so:

math.sqrt(B5**2 - 4*A5*C5)
math.sqrt(0**2 - 4*5*6.5)
math.sqrt(0 - 130)
math.sqrt(-130)

The function math.sqrt doesn't find complex roots. You should use cmath.sqrt instead, as that does (this will require importing cmath at the start of your program).

Using cmath, I get this result:

Problem #5
Root 1:  1.1401754250991378j
Root 2:  1.1401754250991378j

(where j is the square root of -1).

rlms
  • 10,650
  • 8
  • 44
  • 61