数学域错误与计算区分

时间:2019-05-30 01:11:54

标签: python python-3.x

我的程序正在求解用户用a,b和c值输入的二次方程。问题出在我的compute_discriminate函数上。我以为是因为您不能取负数的平方根,所以我说如果d为负,则说没有解。但是,我在第56行遇到错误,说 x1 =(-b + math.sqrt(d))/(2 * a) ValueError:数学域错误

在这种情况下提供帮助将非常有帮助,Python对我来说是新手,我想让它开始工作!

尝试说如果d为负,则说在定义x1和x2之前没有解决方案。

a = 0
b = 0
c = 0
import math


def evaluate_quad_function(a, b, c, x):
    f_of_x = a * (x ** 2) + (b * x) + c
    return f_of_x  # return the calculated result


print("Welcome to the Quadratic Solver for f(x)=ax^2+bx+c")
a = input("Enter Value for a:")
b = input("Enter Value for b:")
c = input("Enter Value for c:")
# cannot do math on string, convert to float
a = float(a)
b = float(b)
c = float(c)
f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c


def print_sign(x):
    # check the sign if positive or negative
    return '+' if x > 0 else '-'


if a == 1:
    print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")
if b == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
if c == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")

x = input("Enter Value for x:")
x = float(x)

fx = evaluate_quad_function(a, b, c, x)
print("F" + "(" + str(x) + ")""=", str(fx))
temp = input("\nPress Enter to continue...")  # wait

x0 = -b / (2 * a)
x0 = float(x0)
if a > 0:
    print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
else:
    print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
temp = input("\nPress Enter to continue...")  # wait


def compute_discriminate():
    print("Solving for f(x) = 0")
    d = (b ** 2) - (4 * a * c)
    if d < 0:
        print("No real solution.")
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print("Discriminant is", str(d))
    if d > 0:
        (print("Two Real Solutions", str(x1), "and", str(x2)))

    if d == 0:
        print("One real solution:", str(x0))



print(compute_discriminate())

2 个答案:

答案 0 :(得分:0)

检查d <0是否为真后,还需要返回/退出该函数,否则它将继续执行。

d = (b ** 2) - (4 * a * c)
if d < 0:
    print("No real solution.")
    return # Exit the function now
x1 = (-b + math.sqrt(d)) / (2 * a)

答案 1 :(得分:0)

Untietled123绝对正确,或者您可以这样做:

assert d>=0

assert表示该功能必须为真 否则会引发错误

如果您想让它带有一条消息,您可以这样做:

try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))

在此之后有大量代码并且您希望代码在遇到该错误时立即结束的情况非常方便。

这样,您不必退出循环或任何事情

最后,

print(compute_discriminate())

您不需要打印功能,我想您可能从未意识到cos每次在完成之前都会出现错误:)

希望它会有所帮助:)

这是一个可以多次求解方程式的版本,我对其进行了一些调整

Untietled123绝对正确,或者您可以这样做:

assert d>=0

assert表示该功能必须为真 否则会引发错误

如果您想让它带有一条消息,您可以这样做:

try:
    assert d>=0
except AssertionError:
    msg = ("no real solution")
    raise AssertionError(msg.format(__file__))

在此之后有大量代码并且您希望代码在遇到该错误时立即结束的情况非常方便。

这样,您不必退出循环或任何事情

最后,

print(compute_discriminate())

您不需要打印功能,我想您可能从未意识到cos每次在完成之前都会出现错误:)

希望它会有所帮助:)

编辑:这是一个版本,您可以多次求解方程式,我对其进行了一些调整,例如摆脱了停顿,但是如果您愿意的话,仍然可以找回它们

import math

print('Credit to Adam Hermon from stack overflow')
'''asked a question, I fixed his code and now I'm using it '''
print("Welcome to the Quadratic Solver for")
print('f(x)=ax^2+bx+c')
done = False
while not done:
    a = input("Enter Value for a:")
    b = input("Enter Value for b:")
    c = input("Enter Value for c:")
    # cannot do math on string, convert to float
    a = float(a)
    b = float(b)
    c = float(c)
    f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c


    def evaluate_quad_function(a, b, c, x):
        f_of_x = a * (x ** 2) + (b * x) + c
        return f_of_x  # return the calculated result

    def print_sign(x):
        # check the sign if positive or negative
        return '+' if x > 0 else '-'


    if a == 1:
        print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x", 
        print_sign(c), abs(c), sep="")
    if b == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ",                                 
        print_sign(c), abs(c), sep="")
    if c == 1:
        print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), 
              "x", print_sign(c), abs(c), sep="")

    x = input("Enter Value for x:")
    x = float(x)

    fx = evaluate_quad_function(a, b, c, x)
    print("F" + "(" + str(x) + ")""=", str(fx))
    ##temp = input("\nPress Enter to continue...")  # wait

    x0 = -b / (2 * a)
    x0 = float(x0)
    if a > 0:
        print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + 
            str(f_x0))
    else:
        print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" +  
            str(f_x0))
    ##temp = input("\nPress Enter to continue...")  # wait


    def compute_discriminate():
    ##    print("Solving for f(x) = 0")
        d = (b ** 2) - (4 * a * c)
        if d < 0 :
            print('No Real Solutions')
            return 'bad'
        x1 = (-b + math.sqrt(d)) / (2 * a)
        x2 = (-b - math.sqrt(d)) / (2 * a)
        print("Discriminant(the stuff under the sqrt sign) is", str(d))
        if d > 0:
            (print("Two Real Solutions", str(x1), "and", str(x2)))

        if d == 0:
            print("One real solution:", str(x0))



    compute_discriminate()
    print('')
    print('Another one? Press enter')
    i = input('if not, type no')
    if i == 'no' or i == 'No' or i == 'NO':
        done = True
    else:
        print('Solving another equation:')