如何在 [-pi;pi] 中插入 sin(1/x)?

How interpolate sin(1/x) in [-pi;pi]?

我在 python 中遇到插值问题。我必须在值部分 [-pi;pi] 中插入 sin(1/x) 并且必须为 0.08 步长生成插值数据。 0.4步的输入数据。问题在于输入数据的值并未在 3.14 结束。同样的情况出现在插值数据中,我不知道如何解决这个问题。两组可能相等。这是我测试这两组的代码:

import numpy as np

//entry x
x=[i for i in np.arange(-(np.pi),np.pi,0.4)]
print(x);

//interpolate x
xinterp=[i for i in np.arange(-(np.pi),np.pi,0.08)]
print(xinterp)

编辑以反映@wwii 的提示:

这是预期的行为。 arange 没有将 stop 作为最终值并且没有很好地定义浮点...

来自: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.arange.html

stop : number End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

请查看 linspace

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.linspace.html.

根据描述:

Returns num evenly spaced samples, calculated over the interval [start, stop].

因此,为了获得 0.8 粒度,您需要的步数等于间隔宽度 (2pi) 除以您想要的粒度。

x = np.linspace(-np.pi, np.pi, int(2 * np.pi / 0.08))
y = np.sin(1/x)