-3

The Quadratic Equation Calculator and the code that I used didn't work well. There are some errors on the code.

I already tried with basic numbers, like 1/2/3. No equation. Still the code doesn't works. The things that actually work is putting the variable only and that's all. After I press enter to see what is the answer, it said that my code has some errors on it.

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)

I expect to answer the questions properly and this equation calculator can be used for real equations and using variables. x square and 3x and something like that.

MS_092420
  • 5
  • 1
  • 1
  • 4
  • 2
    The easiest way in this particular case is `x*x`. – Code-Apprentice Oct 14 '19 at 15:59
  • 1
    "Still the code doesn't works." What does it do? What do you expect it to do instead? – Code-Apprentice Oct 14 '19 at 16:00
  • 1
    The more generic syntax is `x**2`. That said, I'm not sure this is a good SO question -- certainly, the code is much more than a *minimal* [mre] (which should be the *shortest possible thing* that can demonstrate a very specific error, with both expected and actual outputs made clear). – Charles Duffy Oct 14 '19 at 16:00
  • *"...code has some errors on it."* is not a good error description atleast on SO. – Austin Oct 14 '19 at 16:01
  • 1
    ...part of "shortest possible" is that if your problem isn't with user input, *don't do user input at all*, just hardcode some specific values that show your problem; that also lets you show both expected and actual outputs for those very specific values. See also the "Tricks for Trimming" section at http://sscce.org/. – Charles Duffy Oct 14 '19 at 16:02
  • "After I press enter to see what is the answer, it said that my code has some errors on it" What errors are you seeing? – RFairey Oct 14 '19 at 16:05
  • Please show what input you typed and the **exact error message** in your question. – Code-Apprentice Oct 14 '19 at 16:07
  • Also, do the calculation with a hand-held calculator. This will help you understand what is happening. – Code-Apprentice Oct 14 '19 at 16:08
  • Try 1/3/2 for your input instead of 1/2/3. – Code-Apprentice Oct 14 '19 at 19:44

5 Answers5

1

In python 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 being 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}.

This can be easily tackled by gauging the "discriminant".

The discriminant is b^2 - 4ac, and

  • if discriminant = 0, then there is only one solution
  • if discriminant > 0, then there are two real solutions
  • if discriminant < 0, then there are two complex solutions

Considering above conditions, the code should look so:

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)

Similar SO answers: https://stackoverflow.com/a/49837323/8247412

Below I have altered the code in favour of pythonic programming, as numpy can find roots of polynomial (quadratic and higher order) equations with prowess. numpy.roots

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)
0

It looks like you are trying to find the roots of a quadratic function y = a*x^2 + b*x + c. Depending on the values of a, b, and c. (Note you should use these variable names instead of first, second and third because they are the commonly used mathematical names.)

Depending on the values of a, b, and c, the roots might be complex numbers. I suggest you start with some values that you know will give real, not complex, solutions.

In Python, when you attempt to take the square root of a negative number, you will get an error. If you want to be able to calculate the complex roots, you need to learn how to use complex numbers in Python.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 2
    This seems largely speculative -- something that *could* be an unambiguously on-point answer if we required the OP to show specific inputs and a specific error arising therefrom and they affirmed the speculation at hand, but right now is more a guess that might be better-suited to being a comment than an answer. – Charles Duffy Oct 14 '19 at 16:05
  • @CharlesDuffy Yes, it is a guess on my part and I have asked for clarification in a comment. – Code-Apprentice Oct 14 '19 at 16:06
  • @CharlesDuffy Looking more closely at the question, the OP writes "I already tried with basic numbers, like 1/2/3." I think this means that these are the input values that he tried. If so, then the resulting quadratic function has complex roots. – Code-Apprentice Oct 14 '19 at 16:37
0

Try this. I recommend using shorter names for variables. You can replace "import numpy as np" with "import cmath" and replace "np.lib.scimath" with "cmath" if you haven't installed numpy. QES stands for quadratic equation solver.

#Import package
import numpy as np

#Define a new function called qes
def qes(a1,b1,c1):

    ans1=((-1*b1)+np.lib.scimath.sqrt((b1**2)-(4*a1*c1)))/(2*a1)
    ans2=((-1*b1)-np.lib.scimath.sqrt((b1**2)-(4*a1*c1)))/(2*a1)

    return ans1,ans2

#With the defined function perform a calculation and print the answer
ans1,ans2=qes(1,2,1)
print('Answer 1 is: ',ans1,' Answer 2 is: ',ans2)
Cam K
  • 127
  • 2
  • 2
  • 13
  • How is this different than the code in the original question? The only difference I see is the variable names. I agree that shortening them in this way makes a lot of sense, but it doesn't solve any errors. – Code-Apprentice Oct 14 '19 at 16:32
  • Runs fine on my system. I do not know what errors you are experiencing. I updated my answer to be a function and to use numpy instead. – Cam K Oct 14 '19 at 18:07
  • You are using different inputs than what the OP gave. What happens when you call `qes(1,2,3)`? Also, I think that introducing numpy for a clear beginner question will only create confusion for them. – Code-Apprentice Oct 14 '19 at 19:40
  • Does OP want imaginary numbers back? I'd imagine that OP simply wants to solve simple quadratic equations provided in textbooks. Also using numpy in this context is no different from using math. It also puts OP on the path to learning more advanced functions later. – Cam K Oct 15 '19 at 08:09
  • I edited it again to use np.lib.scimath.sqrt so that complex roots can be returned. – Cam K Oct 15 '19 at 08:19
  • "Does OP want imaginary numbers back?" That is unknown since the OP hasn't responded to any comments for clarification nor posted the exact error message they are getting. For the example input given, the error is almost certainly due to taking the square root of a negative number. – Code-Apprentice Oct 15 '19 at 15:39
0

Thank you for all of the supports. But I already answered my question. I think I didn't give any detail about the problem that I had. But I know what code that I use. I made this code that used, not only the quadratics equations problems but it will help you find the minimum point of the quadratics equations. The code:

    import math

print("Quadratics Equation Calculator")
repeat = "yes"
while repeat.lower() == "yes":

    V = float(input("Enter how many Variables do you have in the question: "))
    print(V)
    if V == 3:
        a = float(input("Enter the first variable: "))
        print(a)
        b = float(input("Enter the second variable: "))
        print(b)
        c = float(input("Enter the third variable: "))
        print(c)
        root_1 = ((-1 * b) + math.sqrt((b ** 2) - (4 * a * c))) / (2 * a)
        root_2 = ((-1 * b) - math.sqrt((b ** 2) - (4 * a * c))) / (2 * a)
        print(f"The first result is {root_1} to {round(root_1)}")
        print(f"The second result is {root_2} to {round(root_2)}")
        graph = str(input("Want minimum point: "))
        if graph == "yes":
            x = ((b / 2) * -1)
            y = c - b ** 2/4*a
            print(f"The minimum point is ({x}, {y})")
        elif graph == "no":
            repeat = str(input("Do you wish to continue?: "))
            if repeat == "no":
                break
        else:
            repeat = str(input("Do you wish to continue?: "))
            if repeat == "no":
                break

    elif V == 2:
        a = float(input("Enter the first variable: "))
        print(a)
        b = float(input("Enter the second variable: "))
        print(b)
        root_1 = ((-1 * b) + math.sqrt((b ** 2) - (4 * a * 0))) / (2 * a)
        root_2 = ((-1 * b) - math.sqrt((b ** 2) - (4 * a * 0))) / (2 * a)
        print(f"The first result is {root_1} to {round(root_1)}")
        print(f"The second result is {root_2} to {round(root_2)}")

    else: 
        print("INVALID ERRORS, CHECK AGAIN YOUR VARIABLES")
        print("Type yes or no.")

    repeat = str(input("Do you wish to continue?: "))
    if repeat == "no":
        break

Thank you for all of the answers that you guys gave me and also the formula of it.

MS_092420
  • 5
  • 1
  • 1
  • 4
0

X^2 is a bit-wise XOR operator in python. you can rewrite your equation as x**2(exponential),x*x or pow(x,2) in python

Suman Astani
  • 1,181
  • 11
  • 16