python - 在 Sagemath 中积分并绘制分段函数

标签 python sage

我正在尝试使用 Sagemath 积分分段函数,但发现这是不可能的。我的原始代码如下,但由于描述的意外评估而导致错误 here .

def f(x):
    if(x < 0):
        return 3 * x + 3
    else:
        return -3 * x + 3

g(x) = integrate(f(t), t, 0, x)

网站上提到的绘图修复是使用 f 而不是 f(t),但这显然不支持 integrate() 函数,因为引发了 TypeError

是否有我不知道的解决方法?

最佳答案

不是通过 def 定义分段函数,而是使用内置的 piecewise class :

f = Piecewise([[(-infinity, 0), 3*x+3],[(0, infinity), -3*x+3]]) 
f.integral()

输出:

Piecewise defined function with 2 parts, [[(-Infinity, 0), x |--> 3/2*x^2 + 3*x], [(0, +Infinity), x |--> -3/2*x^2 + 3*x]]

分段函数有自己的方法,例如.plot()。但是,绘图不支持无限间隔。可以得到有限区间的图

f = Piecewise([[(-5, 0), 3*x+3],[(0, 5), -3*x+3]]) 
g = f.integral()
g.plot()

但是您还想从 g 中减去 g(0)。这不像 g-g(0) 那样简单,但也不算太糟糕:使用 g.list() 获取片段列表,从每个函数中减去 g(0),然后重新组合。

g0 = Piecewise([(piece[0], piece[1] - g(0)) for piece in g.list()])
g0.plot()

就这样了:

plot

通过扩展这种方法,我们甚至不需要从一开始就在 f 中放入有限区间。下面通过修改域在给定区间 [a,b] 上绘制 g - g(0):

a = -2
b = 3
g0 = Piecewise([((max(piece[0][0], a), min(piece[0][1], b)), piece[1] - g(0)) for piece in g.list()])
g.plot()

plotrange

关于python - 在 Sagemath 中积分并绘制分段函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682542/

相关文章:

python - pmml 中的朴素贝叶斯特征向量

ubuntu - sage -i -> sage-run 收到未知选项 : -i

python - jupyter 笔记本 vs jupyter 控制台 : display of markdown (and latex, html 等)对象

python - 在 Sage 中使用 gnuplot 时出错,但在常规 Python 中工作正常

immutability - Sage 不可变向量错误

python - PLY:C 解析器中的 token 移位问题

python - split:更快地找到元素的方法?

python - 如何根据键对字典值求和?

python - 如何将中间件添加到 Pythons 记录器

python - Sage:如何进行 CNFEncode?