如何在python代码中编写x^2?有人能给我关于化学需氧量的建议吗

2024-03-28 21:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的二次方程计算器和代码都不好用。 代码中有一些错误。你知道吗

我已经试过基本数字了,比如1/2/3。没有方程式。代码仍然不起作用。 真正起作用的是只把变量放进去,仅此而已。 在我按下回车键查看答案后,它说我的代码有一些错误。你知道吗

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)

我希望回答正确的问题,这个方程计算器可以用于实际方程和使用变量。x正方形和3x之类的。你知道吗


Tags: the代码input错误mathsqrtfloatvariable
3条回答

看起来你想找到一个二次函数的根y = a*x^2 + b*x + c。取决于abc的值。(注意您应该使用这些变量名,而不是firstsecondthird,因为它们是常用的数学名称。

根据abc的值,根可能是复数。我建议你从一些你知道的能给出真实而不是复杂的解决方案的价值观开始。你知道吗

在Python中,当您尝试取一个负数的平方根时,您将得到一个错误。如果希望能够计算复数根,则需要学习如何在Python中使用复数。你知道吗

在python x^2中,可以是x**2,x*x或pow(x,2)。 其他人给了你很好的建议,我想补充几点。 二次方程:ax^2+bx+c=0(调整使方程等于零!) 具有多项式项ax^2,bx,c;其系数为a,b,c为常数项。 然后二次公式:(-b+sqrt(b^2-4*a*c))/2a;解x

以上所有内容都正确地出现在您的代码中 但是,如果解停留在复数集合{C}中,您将遇到麻烦。你知道吗

这可以很容易地通过测量“判别式”来解决。你知道吗

判别式是b^2-4ac,并且

  • 如果判别式=0,则只有一个解
  • 如果判别式大于0,则有两个实解
  • 如果判别式<;0,则有两个复解

考虑到上述条件,代码应该是这样的:

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)

类似的答案:https://stackoverflow.com/a/49837323/8247412

下面我修改了pythonic编程的代码,因为numpy可以很好地找到多项式(二次和高阶)方程的根。 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)

试试这个。我建议对变量使用较短的名称。您可以将“import numpy as np”替换为“import cmath”并替换np.lib.scimath软件如果您还没有安装numpy,请使用“cmath”。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)

相关问题 更多 >