CodexBloom - Programming Q&A Platform

Unexpected results when using np.meshgrid for non-linear space sampling in NumPy 1.24.0

👀 Views: 162 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
numpy meshgrid sampling Python

I've searched everywhere and can't find a clear answer. I've spent hours debugging this and I'm stuck on something that should probably be simple. I'm trying to create a grid of points in a 2D space using `np.meshgrid` for non-linear sampling, but I'm getting unexpected results. I want to sample points more densely in the center and more sparsely at the edges. Here's the code I'm using: ```python import numpy as np # Define the non-linear space for sampling x = np.linspace(-10, 10, 100)**2 # Squared function for non-linear spacing y = np.linspace(-10, 10, 100) # Generate the meshgrid X, Y = np.meshgrid(x, y) # Check the shapes and first few points print(X.shape, Y.shape) print(X[:5, :5]) print(Y[:5, :5]) ``` When I run this code, I expect `X` to have more points clustered near zero, but it seems to distribute them across the entire range instead. The output shapes of `X` and `Y` are both (100, 100), which is correct, but the values in `X` are not what I anticipated. After examining, I realized that using the squared function in `np.linspace` is not giving me the desired distribution in terms of the grid. I tried using more control by adjusting the spacing with `np.linspace` parameters but I still need to get the non-linear distribution I need. Any insights on how to correctly achieve this or if there's a better approach? I've also looked into `np.arange` but it doesn't seem to fit my use case since I need continuous values. Any suggestions or alternate methods? My development environment is Linux. Am I missing something obvious? What are your experiences with this? Cheers for any assistance!