FooBar
FooBar

Reputation: 16488

Numpy: Generate grid according to density function

linspace generates a linear space. How can I generate a grid using an arbitrary density function?

Say, I would like to have a grid from 0 to 1, with 100 grid points, and where the density of points is given by (x - 0.5)**2 - how would I create such a grid in Python?

That is, I want many grid-points where the function (x - 0.5)**2) is large, and few points where the function is small. I do not want a grid that has values according to this function.

Upvotes: 1

Views: 947

Answers (2)

thomas
thomas

Reputation: 1813

In that case the following solution should work. Be sure that func is positive throughout the range...

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

Upvotes: 2

thomas
thomas

Reputation: 1813

For example like this:

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

The start and end values have to be chosen so that f(start) = 0 and f(end)=1.

Upvotes: 2

Related Questions