Python Numpy:根据密度函数生成网格

Python Numpy:根据密度函数生成网格,python,numpy,scipy,Python,Numpy,Scipy,linspace生成线性空间。如何使用任意密度函数生成网格 比如说,我想要一个从0到1的网格,有100个网格点,其中点的密度由(x-0.5)**2-我如何在Python中创建这样的网格 也就是说,我希望在函数(x-0.5)**2)较大的地方有许多网格点,在函数较小的地方有几个网格点。我不希望网格具有符合此函数的值。例如: x = (np.linspace(0.5,1.5,100)-0.5)**2 必须选择起始值和结束值,以便f(开始)=0和f(结束)=1,在这种情况下,以下解决方案应该有效。确

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

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

也就是说,我希望在函数
(x-0.5)**2)
较大的地方有许多网格点,在函数较小的地方有几个网格点。我不希望网格具有符合此函数的值。

例如:

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

必须选择起始值和结束值,以便
f(开始)=0
f(结束)=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()