Python 返回数学错误(除0等),否则会使方法崩溃

Python 返回数学错误(除0等),否则会使方法崩溃,python,Python,我正在做一个简单的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

我正在做一个简单的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=x时返回0除错误)。在这些情况下,我如何向用户返回一个文本字符串,通知他们在间隔中没有最小/最大值(或者,与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))

我不确定当您有未定义的结果时,如何定义最小值或最大值。您可以使用未定义结果周围的限制来了解您接近未定义值的方向。
但是,如果只想返回已定义值的最小值或最大值,可以在for循环内移动try块,例如:

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的异常处理。例如:

try:
  foo = 1/0
# catch a specific error
except ZeroDivisionError:
  foo = 0
  print("Division by zero")
# catch all
except Exception as err:
  foo = None
  print("Something really bad happened:", err)
在您的情况下,应该将开始/结束值包装在
try:。。。除此之外:…
用于捕获函数是否定义在极端情况下


请注意,通过采样可能无法检查任意函数是否存在最大/最小值!任何+/-inf值都可能位于您根本不采样的任意点。

只需在for循环之前添加一个if条件,并检查x是否为0。 如果x=0,则只需打印一个文本字符串,否则运行for循环并打印结果

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)
      if x = 0:
        print('divided by zero')
      else:
        print("This function's minimum value is", min(listY))
        print("This function's maximum value is", max(listY)) 

通过使用
if
条件。或
尝试
除了适当的错误
之外,在
eval(Fx)
时,您没有在任何地方使用x的值。该循环只是在没有参数的情况下重复计算用户键入的函数。@BilltheLizard我假设用户键入类似“log(x)”的内容,这应该会起作用。@BilltheLizard
eval
在用户键入x时自动计算x。例如,当用户在
x+1
中键入时,每次循环时,它都会计算
x+1
是什么,并将其添加到列表
listY
。好的,现在如何处理“当log(x)的情况是,有一个最大值而不是最小值时,如何打印[仅]最大值?”我不确定当您有一个未定义的值时,如何定义最小值或最大值。但是您可以在for循环中移动try,除非是在for循环中。您可能还需要
除了ValueError:
,这将捕获数学模块函数域错误,例如
math.sqrt(-1)
math.log(0)
。如果我将函数定义为
1/(2-x)
,这也不起作用,例如,如果0是有效值,
x-1
。如果测试在for循环之外,则不会产生任何效果,仍然会引发异常。