如何使用“if/else”修改symphy函数?

2024-10-02 18:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用“if/else”工具修改数学函数g=x³的图像

我需要的是,当我的函数图像大于0时,结果保持不变,但如果图像是其他内容,我希望图像成为1/g的结果

目前我试着这样做:

from sympy import * 
from sympy.abc import x

g = x**3
 
if g > 0:   
   g = g 
else:   
   g = 1/g
 
plot(g) 

但它回答了我这个问题:

File "c:/Users/Anticrate/Desktop/PYTHON Sauvegardes/tes7.py", line 8, in <module>
    if g > 0:
  File "C:\Users\Anticrate\anaconda3\lib\site-packages\sympy\core\relational.py", line 398, in __bool__
    raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational

Tags: 函数infrompy图像importifline
1条回答
网友
1楼 · 发布于 2024-10-02 18:28:20

可以使用Piecewise创建基于符号条件定义的函数:

In [1]: from sympy import Symbol, Piecewise, plot

In [2]: x = Symbol('x')

In [3]: g = Piecewise((x**3, x>0), (1/x**3, True))

In [4]: g
Out[4]: 
⎧ 3           
⎪x   for x > 0
⎪             
⎨1            
⎪──  otherwise
⎪ 3           
⎩x            

In [6]: plot(g, ylim=(-10, 10))
Out[6]: <sympy.plotting.plot.Plot at 0x7f89c4ba61c0>

相关问题 更多 >