Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I don't know how to write x^2 in my python code? Can anyone give me suggestions about my code?

My code doesn't work with the Quadratic equation calculator. I guess, there is some sort of error in the code. My code doesn't work with basic numbers also. It actually works when putting the variable. But, When I try to execute the code, it said that my code has some errors.

print ("Quadratic Equation Calculator")

import math

print ("Enter the first variable : ")

first = float(input(''))

print ("Enter the second variable : ")

second = float(input(''))

print ("Enter the third variable : ")

third = float(input(''))

Answer1 = ((-1 * second) - math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)

Answer2 = ((-1 * second) + math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)

print (Answer1)

print (Answer2)

Can anyone help me out with this issue?

1 Answer

0 votes
by (26.4k points)

In Python, please note, x ^ 2 can be x ** 2, x * x, or pow(x, 2). Others have given you good suggestions, and I would like to add a few. The Quadratic Equation: ax^2 + bx + c = 0 (Adjust to make the equation equal zero!) has polynomial terms ax^2, bx, c; whose coefficients are a, b. And c is the constant term. then the Quadratic formulae: (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a; Solves for x.

All of the above appears rightly in your code, However, you will have trouble if the solutions dwell in complex numbers set {C}.

import math

print ("Quadratic Equation Calculator")

a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))

b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))

c = float(input("Enter the constant term (degree 0), [c]: "))

discriminant = pow(b, 2) - 4.0 * a * c

if discriminant == 0:

    root1 = root2 = (-1 * b) / (2 * a)

elif discriminant < 0:

    root1 = ((-1 * b) - math.sqrt(-discriminant) * 1j) / (2 * a)

    root2 = ((-1 * b) + math.sqrt(-discriminant) * 1j) / (2 * a)

else:

    root1 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)

    root2 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)

print (root1)

print (root2)

Below, I have also altered the below code in the favor of pythonic programming, since NumPy helps us to find the roots of polynomial equations with prowess.

import numpy as np

print ("Quadratic Equation Calculator")

a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))

b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))

c = float(input("Enter the constant term (degree 0), [c]: "))

coeffs = [a, b, c]  # or d, e and so on..

roots = np.roots(coeffs)

print (roots)

Interested to learn more about python, Come and Join: Python online course

Related questions

0 votes
4 answers
0 votes
4 answers
0 votes
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...