因此对于我的程序,我正在解决一个基于用户输入的二次方程。因此,在我的代码中,我想做到的是,当用户为a或b输入1或-1时,而不是写-1x 2 + 1x时,它应该是-x 2 + 1。 但是,当我输入-1并为a和b输入-1时,程序将跳过显示该函数的过程,就像使用其他任何值一样。但是,与其他任何值一样,在尝试使用compute_discriminant函数来解决判别式时,我在代码的第48行指出一条错误: 第48行,compute_discriminate x1 =(-b + math.sqrt(d))/(2 * a) ValueError:数学域错误
尽管a和b分别为-1和-1,该程序在解决判别式上没有问题。
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="")
elif b == 1:
print("\nFunction is: f(x)= ",a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
elif 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)
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))
if d < 0:
print("No real solution.")
print(compute_discriminate())
第48行,在compute_discriminate x1 =(-b + math.sqrt(d))/(2 * a)中 ValueError:数学域错误
预期结果是求解并返回判别函数及其值。