简体   繁体   中英

How to write x^2 in my python code? Can someone give me suggestion about my code

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.

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

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.

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM