문제

I'm writing a program to solve quadratic equations using the quadratic formula but it only works when a = 1 but i want it to work when a is more than 1

Here is my code:

import math

def solve(a, b, c):

    x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
    print "x = %s" %x
    print "or"
    y = ((-1)* b - math.sqrt(b**2-4*a*c))/2*a
    print "x = %s" %x




while 1:
    a = int(raw_input("Enter A :"))
    b = int(raw_input("Enter B :"))
    c = int(raw_input("Enter C :")) 
    solve(a, b, c)

It works with 1 but when I use a number more than one when i use say 4 i get this error

Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\Factor.py", line 18, in <module>
    solve(a, b, c)
  File "C:\Documents and Settings\User\Desktop\Factor.py", line 5, in solve
    x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
ValueError: math domain error

is there a way around this if so help!!

도움이 되었습니까?

해결책

The problems are here:

  1. operator precedence: your /2*a should be /(2*a) to work correctly.
  2. the domain of sqrt: math.sqrt bails on negative numbers.
  3. Edit 2: y = ... just after print "or" should be x = ...

To fix the latter, you'll need some sort of conditional:

disc = b**2 - 4*a*c
sqrtdisc = math.sqrt(disc) if disc >= 0 else math.sqrt(-disc)*1j

Edit: You could also use cmath.sqrt, which automatically handles negative numbers:

disc = b**2 - 4*a*c
sqrtdisc = cmath.sqrt(disc)

(Thanks to various other answerers for effectively letting me know that cmath exists.)

다른 팁

To handle complex numbers use cmath instead.

import cmath
cmath.sqrt(negativenumber)

The reason for why you're getting ValueError is that your expression b**2-4*a*c is returning a negative value, which is not allowed for math.sqrt.

>>> math.sqrt(-1)
Traceback (most recent call last):
  File "<ipython-input-38-5234f21f3b4d>", line 1, in <module>
    math.sqrt(-1)
ValueError: math domain error

use cmath.sqrt to handle negative values as well:

>>> import cmath
>>> cmath.sqrt(-1)
1j

You're getting a math domain error because you're giving a negative value to math.sqrt. This is likely happening as you increase a because you aren't increasing b by enough to have b**2-4*a*c give a positive value.

Try using something like this to get your roots:

def roots(a, b, c):

    def getDiscriminant(a, b, c,Error = "Imaginary Roots"):
        try:
            return (b ** 2 - (4 * a * c)) ** .5
        except:
            return Error

    D = getDiscriminant(a, b, c) 

    if D == False:
        return False

    b = -b
    a = 2 * a

    firstroot = float((b + D) / float(a))
    secondroot = float((b - D) / float(a))

    return (firstroot,secondroot)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top