首页 > 解决方案 > 在 python 中找到临界值,有限集的问题

问题描述

我编写了用于在 Python 中查找临界值的程序。

我的代码:

from sympy import *
def find_critical_points(f, x):
    fd = diff(f)
    dRoots = solveset(fd, x)
    a = Rational(float(dRoots))
    return a

我为此写了测试:

x = Symbol('x')
lst = find_critical_points(x**4+x**3, x)
assert lst == [-3/4,0]
lst = find_critical_points(x,x)
assert lst == []

Python返回错误:

float() 参数必须是字符串或数字,而不是 'FiniteSet'

请帮助解决此错误。

标签: pythonpython-3.x

解决方案


问题是它float()需要一个字符串或一个数字,然后对其进行解析或将其转换为浮点数。

稍加研究,我们可以发现FiniteSet可以直接转入一个 Python 列表。所以你的代码可以是这样的:

from sympy import *


def find_critical_points(f, x):
    fd = diff(f)
    dRoots = solveset(fd, x)
    # a = Rational(float(dRoots))
    return list(dRoots)


x = Symbol('x')
lst = find_critical_points(x**4+x**3, x)
assert lst == [-3/4,0]
lst = find_critical_points(x,x)
assert lst == []

推荐阅读