python - Numerical approximation of forward difference in an interval
问题描述
How can python be used for numerical finite difference calculation without using numpy? For example I want to find multiple function values numerically in a certain interval with a step size 0.05 for a first order and second order derivatives.
解决方案
Why don't you want to use Numpy? It's a good library and very fast for doing numerical computations because it's written in C (which is generally faster for numerical stuff than pure Python).
If you're curious how these methods work and how they look in code here's some sample code:
def linspace(a, b, step):
if a > b:
# see if going backwards?
if step < 0:
return linspace(b, a, -1*step)[::-1]
# step isn't negative so no points
return []
pt = a
res = [pt]
while pt <= b:
pt += step
res.append(pt)
return res
def forward(data, step):
if not data:
return []
res = []
i = 0
while i+1 < len(data):
delta = (data[i+1] - data[i])/step
res.append(delta)
i += 1
return res
# example usage
size = 0.1
ts = linspace(0, 1, size)
y = [t*t for t in ts]
dydt = forward(y, size)
d2ydt2 = forward(dydt, size)
Note: this will still use normal floating point numbers and so there are still odd rounding errors that happen because some numbers don't have an exact binary decimal representation.
Another library to check out is mpmath which has a lot of cool math functions like integration and special functions AND it allows you to specify how much precision you want. Of course using 100 digits of precision is going to be a lot slower than normal floats, but it is still a very cool library!
推荐阅读
- angular - Primeng的p-fileUpload中没有运行onUpload方法
- bash - 重击。在调用堆栈中插入函数调用
- angular - 使用 Angular 8,如何获取对在页面其余部分加载几秒钟后加载的 DOM 元素的引用?
- google-apps-script - 使用 API 将 Google 幻灯片(和绘图)链接到 Google Doc
- flutter - Flutter:列表滚动上的 sliverAppBar 调整大小问题
- node.js - 带有 NodeJs sdk 版本 4.0 的 Microsoft Bot Framework 不允许多个用户会话
- u-boot - 如何在 Coral 开发板启动期间禁用控制台消息?
- django - 如何在Django2.1的模板内的for循环内设置变量?
- scala - 在 scala 项目中创建 power point 并得到导入错误。导入 org.apache.poi.ss.usermodel。尝试导入 ss 作品
- php - PHP表单上的多个签名