我试图用Sympy实现Bisection方法,但我遇到了这个错误。
if f[a]*f[c] > 0: # Opposite sign a and c
File "C:\Users\maico\AppData\Local\Programs\Python\Python38\lib\site-packages\sympy\core\relational.py", line 376, in __nonzero__
raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational
这是我的代码
from sympy import plot_implicit, latex, lambdify, Float
from sympy.abc import x
from sympy.parsing.latex import parse_latex
eq = input("Latex equation: ")
raw_equation = eq.replace("=0", "").replace("= 0", "").replace("e", "E")
equation = parse_latex("y = " + raw_equation)
f = lambdify(x, parse_latex(self.__raw_equation), 'numpy')
# Bisection
a = 0 # start interval
b = 1 # end interval
eps = a - b
r = None
nlimit = 8
for n in range(nlimit):
c = (a + b) / 2
fd = {a: f(a), b: f(b), c: f(c)}
solved = False
for v in [a, b, c]:
if fd[v] == 0:
r = "Iterations: {} - Result: {}".format(n + 1, v)
solved = True
break
if solved:
break
if fd[a]*fd[c] > 0: # Opposite sign a and c <-- ERROR
b = c
else: # Opposite sign b and c
a = c
...
你可以用下面的公式来测试一下 xe^x-1=0
你能帮帮我吗?
有了这些入口
from sympy import plot_implicit, latex, lambdify, Float
from sympy import symbols
from sympy.abc import x
from sympy.parsing.latex import parse_latex
E = symbols('E')
equation = E**x*x - 1
f = lambdify(x, equation, 'numpy')
print(f.__doc__)
....
我得到的是:
1450:~/mypy$ python3 stack61370217.py
Created with lambdify. Signature:
func(x)
Expression:
E**x*x - 1
Source code:
def _lambdifygenerated(x):
return (E**x*x - 1)
Imported modules:
Traceback (most recent call last):
File "stack61370217.py", line 29, in <module>
if fd[a]*fd[c] > 0: # Opposite sign a and c <-- ERROR
File "/usr/local/lib/python3.6/dist-packages/sympy/core/relational.py", line 376, in __nonzero__
raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational
如果换成
from sympy import E
羔羊的表达方式变成了
def _lambdifygenerated(x):
return (x*exp(x) - 1)
它的生产 c
0.00390625
你没有显示定义 E
. 我不知道latex解析是否会产生。 我没有安装足够的包来运行它。 在任何情况下,那个符号 E
传播到 numpy
表达方式:
In [86]: E=symbols('E')
In [87]: def f(x):
...: return E**x*x-1
...:
In [88]: f(10)
Out[88]:
10
10⋅E - 1
In [89]: f(10)*f(20)>0
Out[89]:
⎛ 10 ⎞ ⎛ 20 ⎞
⎝10⋅E - 1⎠⋅⎝20⋅E - 1⎠ > 0
In [90]: if f(10)*f(20)>0: pass
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-90-14ce5e03fbac> in <module>
----> 1 if f(10)*f(20)>0: pass
/usr/local/lib/python3.6/dist-packages/sympy/core/relational.py in __nonzero__(self)
374
375 def __nonzero__(self):
--> 376 raise TypeError("cannot determine truth value of Relational")
377
378 __bool__ = __nonzero__
TypeError: cannot determine truth value of Relational
如果是 E
是同情心的定义 e
这被翻译成 exp(x)
一切都很顺利。