Sympy 解决方案中的 NotImplementedError [英] NotImplementedError in Sympy's solve

查看:29
本文介绍了Sympy 解决方案中的 NotImplementedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一篇关于布隆过滤器的文章,https://en.wikipedia.org/wiki/Bloom_filter,其中为最佳散列函数数导出表达式.我想重现 m = n 的简化情况的计算,即我想确定函数的最小值

I'm reading an article about Bloom filters, https://en.wikipedia.org/wiki/Bloom_filter, in which an expression is derived for the optimal number of hash functions. I'd like to reproduce the computation for the simplified case that m = n, that is, I'd like to determine the minimum of the function

(1-exp(-x))**x

从文章中可以看出,应该发生在 x = ln(2).我尝试使用 sympy 执行此操作,如下所示:

which, from the article, should occur at x = ln(2). I tried doing this with sympy as follows:

In [1]: from sympy import *

In [2]: x, y, z = symbols('x y z')

In [3]: init_printing(use_unicode=True)

In [8]: from sympy.solvers import solve

In [9]: solve(diff((1-exp(-x))**x,x), x)

然而,我得到了一个

NotImplementedError: multiple generators [x, exp(x), log(1 - exp(-x))]
No algorithms are implemented to solve equation x*exp(-x)/(1 - exp(-x)) + log(1 - exp(-x))

我只是想仔细检查一下Sympy是否真的无法解决这个问题?也许我需要在 x 上添加额外的约束/假设?

I would just like to double-check whether Sympy really cannot solve this problem? Perhaps I need to add additional constraints/assumptions on x?

推荐答案

当您遇到无法通过操作符号(解析式求解)来求解方程的问题时,可能仍然可以通过尝试求解不同的数字并得到(或非常接近)正确答案(数字求解).

When you run into this issue where an equation can't be solved by manipulation of symbols (solving analytically), it's possible that it can still be solved by trying different numbers and getting to (or very close to) the correct answer (solving numerically).

您可以将 sympy 解决方案转换为基于 numpy 的函数,并使用 scipy 进行数值求解.

You can convert your sympy solution to a numpy-based function, and use scipy to solve numerically.

from sympy import lambdify
from scipy.optimize import fsolve

func_np = sp.lambdify(x, diff((1-exp(-x))**x,x), modules=['numpy'])
solution = fsolve(func_np, 0.5)

这将解方程为 0.69314718,这正是您所期望的.

This solves the equation as 0.69314718, which is what you expect.

这篇关于Sympy 解决方案中的 NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆