简体   繁体   English

如何在我的 python 代码中写入 x^2? 有人可以给我关于我的代码的建议吗

[英]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.我已经尝试过使用基本数字,例如 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. x 平方和 3x 之类的东西。

In python x ^ 2, can be x ** 2, x * x or pow(x, 2).在 python x ^ 2 中,可以是 x ** 2、x * x 或 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;二次方程:ax^2 + bx + c = 0(调整使方程等于0,)有多项式项ax^2,bx; c, whose coefficients are ab And c being the constant term: then the Quadratic formulae; c,其系数为 ab 和 c 为常数项:则二次公式; (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a. (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a。 Solves for x.求解 x。

All of the above appears rightly in your code However, you will have trouble if the solutions dwell in complex numbers set {C}.以上所有内容都正确地出现在您的代码中但是,如果解决方案停留在复数集合 {C} 中,您将遇到麻烦。

This can be easily tackled by gauging the "discriminant".这可以通过衡量“判别式”轻松解决。

The discriminant is b^2 - 4ac, and判别式是 b^2 - 4ac,并且

  • if discriminant = 0, then there is only one solution如果判别式 = 0,则只有一种解
  • if discriminant > 0, then there are two real solutions如果判别式 > 0,则有两个实解
  • if discriminant < 0, then there are two complex solutions如果判别式 < 0,则有两个复解

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类似的 SO 答案: 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.下面我更改了代码以支持 pythonic 编程,因为 numpy 可以强大地找到多项式(二次和更高阶)方程的根。 numpy.roots 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 .看起来您正试图找到二次 function y = a*x^2 + b*x + c的根。 Depending on the values of a , b , and c .取决于abc的值。 ( Note you should use these variable names instead of first , second and third because they are the commonly used mathematical names. ) 请注意,您应该使用这些变量名称而不是firstsecondthird ,因为它们是常用的数学名称。

Depending on the values of a , b , and c , the roots might be complex numbers.根据abc的值,根可能是复数。 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.在 Python 中,当您尝试取负数的平方根时,会出现错误。 If you want to be able to calculate the complex roots, you need to learn how to use complex numbers in Python.如果你想能够计算复数根,你需要学习如何在 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.如果您尚未安装 numpy,您可以将“import numpy as np”替换为“import cmath”,并将“np.lib.scimath”替换为“cmath”。 QES stands for quadratic equation solver. QES 代表二次方程求解器。

#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 X^2 是 python 中的按位异或运算符。您可以在 python 中将等式重写为 x**2(exponential),x*x 或 pow(x,2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以帮我写代码吗? (Python) - Can someone help me with my code? (python) 有人可以帮我弄清楚如何在我的 python 刽子手代码上更新我的破折号 - May someone help me figure out how to update my dashes on my python hangman code 有人可以帮我处理我的 Python 代码吗? - Could someone please help me with my Python code? 有人可以向我解释为什么我的代码有效吗? (异步蟒蛇) - Could someone explain to me why my code works? (Asyncio python) 有人可以告诉我为什么我的代码不起作用吗? - Can someone tell me why my code isn't working? 有人可以帮助我使用我的随机代码生成器吗? - Can someone please help me with my random code generator? 有没有办法检测消息中的链接? (或者有人可以帮我写代码) - Is there a way to detect a link in a message? (or can someone help me with my code) 有人能告诉我我的代码有什么问题吗 - Can someone tell me what is wrong with my code 有人可以帮我找到代码中错误源的解决方案吗? - Can someone help me find a solution to error source in my code? 有人可以告诉我我的 animation 代码有什么问题吗? - Can someone tell me what's wrong with my animation code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM