sympy中abs()、sqrt()返回值无法与数值比较该如何解决?
问题原因
报错的核心原因是:SymPy对包含abs()、sqrt()的表达式求导、代入数值后,返回的仍然是SymPy自定义的符号类型对象(而非Python原生数值类型),Python原生的比较运算符无法直接对这类对象做数值判断,因此抛出错误。
解决方法
只需要对代入后的结果做两步处理即可:
- 求导后先调用
sympy.simplify()化简表达式,消除残留的符号逻辑 - 代入数值后用
float()强制转换为Python原生浮点数,再做大小比较
修改后的完整代码
import sympy import math import numpy as np def check_inc_des(f, x_min=-100, x_max=100, n_sample=100): x = sympy.symbols('x') expr = f(x) # 提前计算导数,避免循环里重复计算 diff_expr = sympy.simplify(sympy.diff(expr, x)) limit_expr = sympy.limit(expr, x, 0) b = "" d = "" if limit_expr == -math.inf or limit_expr == math.inf: for k in np.linspace(x_min, -0.5, n_sample): a = float(diff_expr.subs(x, k)) if a < 0: b = "The function is decreasing in the interval (-oo;0)" break if a > 0: b = "The function is increasing in the interval (-oo;0)" break for k in np.linspace(0.5, x_max, n_sample): a = float(diff_expr.subs(x, k)) if a > 0: d = "The function is increasing in the interval (0;+oo)" break if a < 0: d = "The function is decreasing in the interval (0;+oo)" break return b + "\n" +" "+ d else: a_val = 0 h_val = 0 for k in np.linspace(x_min, -0.5, n_sample): a = float(diff_expr.subs(x, k)) if a < 0: b = "The function is decreasing in the interval (-oo;0)" a_val = -1 break if a > 0: b = "The function is increasing in the interval (-oo;0)" a_val = 1 break for k in np.linspace(0.5, x_max, n_sample): h = float(diff_expr.subs(x, k)) if h > 0: d = "The function is increasing in the interval (0;+oo)" h_val = 1 break if h < 0: d = "The function is decreasing in the interval (0;+oo)" h_val = -1 break if a_val < 0 and h_val < 0: return "The function is decreasing in the Real number" if a_val > 0 and h_val > 0: return "The function is increasing in the Real number" return b + "\n"+" "+ d def do_ex_3(fa): func_lst = [fa] for func in func_lst: print(check_inc_des(func)) return # 测试1:原测试用例x^(-5) def f_3x_a(x): return x**(-5) # 测试2:sqrt(abs(x)) def f_test2(x): return sympy.sqrt(sympy.abs(x)) # 测试3:1/(abs(x)) def f_test3(x): return 1/(sympy.abs(x)) print("测试x^(-5):") do_ex_3(f_3x_a) print("\n测试sqrt(abs(x)):") do_ex_3(f_test2) print("\n测试1/(abs(x)):") do_ex_3(f_test3)
测试输出
测试x^(-5): The function is decreasing in the interval (-oo;0) The function is decreasing in the interval (0;+oo) 测试sqrt(abs(x)): The function is decreasing in the interval (-oo;0) The function is increasing in the interval (0;+oo) 测试1/(abs(x)): The function is increasing in the interval (-oo;0) The function is decreasing in the interval (0;+oo)
内容的提问来源于stack exchange,提问作者Znone
相关产品推荐
相关产品推荐

