Atharv Nadkarni
Atharv Nadkarni

Reputation: 33

ValueError when coding quadratic formula

I am coding the quadratic formula in Python. The following function is supposed to solve x^2-x-20. If you do the math you get -4 and 5.

# Quadratic Formula
from math import sqrt
def findsolutions(a, b, c):
    """
    Find solutions to quadratic equations.
    """
    x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
    x2 = (-b - sqrt(b^2-4*a*c))/(2*a)
    return x1, x2

x1, x2 = findsolutions(1,-1,-20)
print("The solutions to x^2-x-20 are", x1, "and", x2)

However, if you run it, you get:

Traceback (most recent call last):
  File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 11, in <module>
    x1, x2 = findsolutions(1,-1,-20)
  File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 7, in findsolutions
    x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
ValueError: math domain error

So what is going on?

Upvotes: 0

Views: 88

Answers (1)

Ram
Ram

Reputation: 4779

In Python, ^ is a Bitwise operator called XOR (Exclusive-OR)

I think you've mistook it for calculating power. In python you calculate power using **.

x ** y - x raised to the power y

So fix your code like this

x1 = (-b + sqrt(b**2-(4*a*c)))/(2*a)

Upvotes: 2

Related Questions