Numpy:根据密度函数

时间:2015-12-01 10:09:31

标签: python numpy scipy

linspace生成线性空间。如何使用任意密度函数生成网格?

说,我想有一个从0到1的网格,有100个网格点,点的密度由(x - 0.5)**2给出 - 我将如何在Python中创建这样的网格?

也就是说,我想要函数(x - 0.5)**2)很大的很多网格点,以及函数小的几点。我想要一个根据此功能具有值的网格。

2 个答案:

答案 0 :(得分:2)

例如:

x = (np.linspace(0.5,1.5,100)-0.5)**2

必须选择开始和结束值,以便f(start) = 0f(end)=1

答案 1 :(得分:1)

在这种情况下,以下解决方案应该有效。确保func在整个范围内都是正面的......

import numpy as np
from matplotlib import pyplot as plt

def func(x):
    return (x-0.5)**2

start = 0
end = 1
npoints = 100

x = np.linspace(start,end,npoints)
fx = func(x)

# take density (or intervals) as inverse of fx
# g in [0,1] controls how much warping you want.
# g = 0: fully warped
# g = 1: linearly spaced
g = 0 
density = (1+g*(fx-1))/fx

# sum the intervals to get new grid
x_density = np.cumsum(density)
# rescale to match old range
x_density -= x_density.min()
x_density/= x_density.max()
x_density *= (end-start)
x_density += start


fx_density = func(x_density)

plt.plot(x,fx,'ok',ms = 10,label = 'linear')
plt.plot(x_density,fx_density,'or',ms = 10,label = 'warped')
plt.legend(loc = 'upper center')

plt.show()

enter image description here