使用numpy的Python差异未产生预期的输出 [英] Python differentiation using numpy not producing expected output

查看:84
本文介绍了使用numpy的Python差异未产生预期的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在做一些数值计算.我已经计算了只能通过数值计算的函数(return_times)的大约100,000点,现在想使用numpy.gradient将其推导.据我了解( doc ), (x)我可以给出以下参数:numpy.gradient(arr_of_fx_datapoints, arr_of_their_x_values)使其起作用.这就是我(打算做的)事情.

So, I am working on some numerical computation. I have calculated some 100,000 points of a function (return_times) only computable numerically, and now want to take it's derivate using numpy.gradient. As I understand (doc), for an f(x)I can give the following arguments: numpy.gradient(arr_of_fx_datapoints, arr_of_their_x_values) to make it work. And that's what I (intended to) do.

除非它不起作用.结果到处几乎(但不完全)为零.该错误由下面的我的代码摘要重现(sin ^ 2(x)的形状类似于我的原始函数):

Except that it doesn't work. The result is almost (but not exactly) zero everywhere. The bug is reproduced by this abstract of my code below (sin^2(x) has a shape alike to my original function):

import matplotlib.pyplot as plt
import numpy as np

def find_times(t_arr):
    return np.power(np.sin(t_arr), 2)

t_0 = 0
t_max = np.pi-1E-10
datapoints = 100000

dt = (t_max - t_0) / datapoints
t_points = np.arange(t_0, t_max, dt, dtype=np.float64)
return_times = find_times(t_points)
gd = np.gradient(return_times, t_points)
plt.plot(t_points, gd)
plt.plot(t_points, return_times)
plt.show()

结果令人失望:

The result is disappointing:

如果我打印gd,则表明它确实不是完全为零:

If I print gd, it shows it is indeed not entriely zero:

[             inf   6.28318530e-05   6.28318529e-05 ...,  -1.25666419e-09
  -6.28326813e-10  -3.14161265e-10]

所以:我想念什么?用Python进行数值推导的最终正确方法是什么?

So: What did I miss? What is the Ultimate Proper Way to numerically derivate in Python?

环境:Linux Mint 18.2 OS,Geany编辑器,NumPy 1.11.0.

Enviroment: Linux Mint 18.2 OS, Geany editor, NumPy 1.11.0.

推荐答案

文档没有提到它,但是坐标数组支持是非常新的NumPy 1.13.在以前的NumPy版本中,您只能为每个维度指定固定的标量阶跃值.

The docs don't mention it, but coordinate array support is very new, NumPy 1.13. In previous NumPy versions, you can only specify a fixed scalar step value for each dimension.

NumPy 1.12可以检查非标量步骤,但是您正在使用的NumPy 1.11不会注意到数组值的输入,并且通过尝试将数组视为一步来默默地做错了事情.

NumPy 1.12 has a check to catch non-scalar steps, but NumPy 1.11, which you're on, doesn't notice the array-valued input and silently does the wrong thing by trying to treat the array as a step.

这篇关于使用numpy的Python差异未产生预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆