简体   繁体   English

为什么lambdify永远不会停止?

[英]Why lambdify never stops?

x = symbols('x')
ch = 'exp(cos(cos(exp((sin(-0.06792841536110628))**(-6.045461643745118)))))'
f = lambdify(x, ch, "numpy")
print(float(f(2)))

It does not work, the programm is running and never ends(no error is issued).它不起作用,程序正在运行并且永远不会结束(没有发出错误)。 My goal is to avoid this kind of cases (among multiple cases) by doing a try/except but i can't as there is no error Why no error is released?我的目标是通过尝试/除外来避免这种情况(在多种情况下),但我不能因为没有错误为什么没有错误被释放? How can i avoid these cases?我怎样才能避免这些情况?

Thanks for your helping me !谢谢你帮助我!

In general, I'm not sure you can.一般来说,我不确定你能做到。 SymPy or NumPy will keep trying to compute the number until precision is exhausted. SymPy 或 NumPy 将继续尝试计算数字,直到精度耗尽。 But you can create a function that will raise and error if numbers are out of bounds for your interest:但是您可以创建一个 function 如果数字超出您的兴趣范围,它将引发和错误:

>>> from sympy import cos as _cos, I, exp
>>> def cos(x):
...     if abs(x) > 10**20: raise ValueError
...     return _cos(x)
>>> exp(cos(cos(exp(5*(1+I)))))
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 2, in cos
ValueError
>>> f = lambda x: exp(cos(cos(exp(x))))
>>> f(sin(-0.06792841536110628)**-6.045461643745118)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
  File "<string>", line 2, in cos
ValueError

But you have to think carefully about when you want to raise such an error.但是您必须仔细考虑何时要引发此类错误。 For example, SymPy has no trouble computing f(100) or f(100*I) if the non-error-catching cos is used.例如,如果使用非错误捕获cos ,SymPy 计算f(100)f(100*I)不会有问题。 So think about when actually you want the error to rise.因此,请考虑一下您实际上希望错误上升的时间。

lambdify is a lexical translator, converting a sympy expression to a python/numpy function. lambdify是一个词法翻译器,将 sympy 表达式转换为 python/numpy function。

Make a string with a symbol:用符号创建一个字符串:

In [27]: ch = 'exp(cos(cos(exp((sin(x))**(-6.045461643745118)))))'

sympify(ch) has no problem, because it doesn't need to do any numeric calculation. sympify(ch)没有问题,因为它不需要做任何数值计算。 So lambdify also works:所以lambdify也有效:

In [28]: f=lambdify(x,ch)
In [29]: f?
Signature: f(x)
Docstring:
Created with lambdify. Signature:

func(x)

Expression:

exp(cos(cos(exp((sin(x))**(-6.045461643745118)))))

Source code:

def _lambdifygenerated(x):
    return (exp(cos(cos(exp(sin(x)**(-6.045461643745118))))))

The equivalent mpmath :等效的mpmath

def _lambdifygenerated(x):
    return (exp(cos(cos(exp(sin(x)**(mpf((1, 54452677612106279, -53, 56))))))))

And a working numeric evaluation:和一个有效的数字评估:

In [33]: f(0j)
Out[33]: mpc(real='nan', imag='0.0')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM