我正在做一个简单的 Python 练习:要求用户提供一个数学公式 f(x),然后计算该公式以找到 x=0 和 x=10 之间 x 的最小值/最大值(采样率) x/100。我写的代码如下:
from math import *
def compute_min_and_max():
Fx = input("what is the desired function of x?" )
listY = []
for i in range(0,1001):
x = i/100
y = eval(Fx)
listY.append(y)
print("This function's minimum value is", min(listY))
print("This function's maximum value is", max(listY))
它工作得很好,除非用户要求像 log(x) 这样的公式,它返回域错误(对于 x=0),或 1/(x-a)(当 a= 时返回除以 0 的错误) X)。在这些情况下,我如何向用户返回一个文本字符串,通知他们间隔中没有最小/最大值(或者,当 log(x) 的情况时,有最大值但没有最小值,如何打印最大值?)
最佳答案
用 try: except: else: block 包裹你的语句
Fx = input("what is the desired function of x?" )
listY = []
try:
for i in range(0,1001):
x = i/100
y = eval(Fx)
listY.append(y)
except ZeroDivisionError:
print("Divide by zero error for f({})".format(x))
except ValueError:
print("Invalid value for f({})".format(x))
else:
print("This function's minimum value is", min(listY))
print("This function's maximum value is", max(listY))
当您有未定义的结果时,我不确定如何定义最小值或最大值。您可以使用未定义结果的限制来了解您接近未定义值的方向。
但是,如果您只想返回定义的值的最小值或最大值,您可以将 try block 移动到 for 循环内,例如:
Fx = input("what is the desired function of x?" )
listY = []
undefined = False
for i in range(0,1001):
try:
x = i/100
y = eval(Fx)
except ZeroDivisionError:
print("Divide by zero error for f({})".format(x))
undefined = True
except ValueError:
print("Invalid value for f({})".format(x))
undefined = True
else:
listY.append(y)
if undefined:
print("Ignoring undefined results")
print("This function's minimum value is", min(listY))
print("This function's maximum value is", max(listY))
关于python - 返回数学错误(除以 0 等),否则会导致方法崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762262/