使用 mpmath 在 Python 中取拉普拉斯逆 [英] Laplace inverse in Python with mpmath
问题描述
我想使用DE HOOG"算法进行数值拉普拉斯逆变换.我想使用mpmath"包,我从链接安装它:
I want to use "DE HOOG" algorithm for numerical Laplace inverse transform. I want to use the "mpmath" package and I installed it from the link:
https://github.com/klkuhlm/mpmath
假设我需要在 t=1 处找到以下函数的拉普拉斯逆变换:
Lets say I need to find the inverse Laplace transform of the below function at t=1:
f = 1/(s-1)
f = 1/(s-1)
f 的拉普拉斯逆变换为:e^(t)
The inverse Laplace transform of f is : e^(t)
在 t=1 时,结果应该是 = e
At t=1 the result is expected to be = e
import mpmath as mp
import numpy as np
def f(s):
return 1 / (s-1)
t = np.linspace(0.01,0.5,10)
G = []
for i in range(0,4):
G.append(mp.invlapdehoog(f, t[i]))
print G
问题是只有当我将i"的范围设置为小于 4 时它才能完美运行.例如,一旦我替换:
The thing is it works perfectly only when I set the range of the "i" less than 4. For example once I substitute:
for i in range(0,5): #or for i in range(0,more than 5):
我收到此错误:
你能帮我解决这个问题吗?
Could you please help me fix this problem?
谢谢!
推荐答案
对象 InverseLaplaceTransform
有一个属性 degrees
,它规定了达到给定水平所需的近似水平的精度.您的 InverseLaplaceTransform
副本每次使用越来越小的值调用它时都会更新 degrees
.最终,degrees
非常小,参数 fp
只有一个值,不足以继续进行进一步的计算.
The object InverseLaplaceTransform
has an attribute degrees
that dictates the levels of approximation necessary to achieve a given level of precision. Your copy of InverseLaplaceTransform
updates degrees
each time you call it with a smaller and smaller value. Eventually, degrees
is so small the parameter fp
has only one value, which is not enough to continue with further calculations.
解决方案:编辑您对 invlapdehoog
的调用以每次重置度数.不过我建议直接调用 invertlaplace
而不是 invlapdehoog
.
Solution: edit your call to invlapdehoog
to reset degrees each time. I suggest however calling invertlaplace
directly rather than invlapdehoog
.
for i in xrange(0,10):
G.append(mp.invertlaplace(f, t[i], method = 'dehoog', degree = 18))
原始海报在对此解决方案的评论中提出了相关问题.他们问为什么随着对 mp.invertlaplace
的连续调用,计算时间会增加(相当显着).简而言之,mp.invertlaplace
正在更新它的属性精度,这决定了它在计算拉普拉斯逆时应该计算多少个小数位.与上述解决方案一样,我们可以将精度传递给每个调用,以确保我们获得所需的精度(例如 - 10 位小数):
The original poster asked a related question in the comments to this solution. They asked why the computation time increases (quite drastically) with consecuitve calls to mp.invertlaplace
. In short, the mp.invertlaplace
is updating its attribute precision which dictates how many decimal places it should compute in calculating the inverse laplace. As with the above solution, we can pass in precision to each call to make sure we obtain the precision we want (eg - 10 decimal places):
for i in xrange(0,10):
G.append(mp.invertlaplace(f, t[i], method = 'dehoog', dps = 10, degree = 18))
PS - 您可以使用以下代码段一次对所有 t 应用反拉普拉斯:
PS - you can apply the inverse laplace to all of t at once with the following snippet:
G = map( lambda x: mp.invertlaplace(f, x, method = 'dehoog', dps = 10, degree = 18), t)
这篇关于使用 mpmath 在 Python 中取拉普拉斯逆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!