如何生成0-3区间靠近3处更密集的非均匀NumPy采样序列?
Great question! To create a sequence from 0 to 3 where points are sparser at the start (0) and denser near the end (3), we need a transformation that produces larger steps early on and smaller steps as we approach 3. Here are a few robust, mathematically clear ways to achieve this:
Method 1: Inverted Logarithmic Transformation
Your initial logarithmic approach created density near 0 because logarithmic functions grow slowly at low values. To flip this, we can generate a log-dense sequence near 0, then invert it to shift the density to 3:
import numpy as np # Generate a log-dense sequence from 0 to 3 (dense at 0) log_dense_at_0 = 3 * (np.logspace(np.log10(1), np.log10(1001), 100) - 1) / 1000 # Invert and reverse to get dense at 3, ordered from 0 to 3 log_dense_at_3 = np.flip(3 - log_dense_at_0)
- How it works:
np.logspacecreates points from 1 to 1001 (logarithmically spaced, so dense near 1). Subtract 1 to shift to 0–1000, scale to 0–3. Subtract from 3 to flip the density to the upper end, then reverse to get the sequence in 0→3 order.
Method 2: Power Function (Fractional Exponent)
Using a fractional exponent (between 0 and 1) on a linear sequence will make values grow quickly at first, then slow down near 3—exactly the density pattern we want:
# Linear base sequence from 0 to 1 lin_base = np.linspace(0, 1, 100) # Apply fractional exponent and scale to 0–3 power_dense_at_3 = 3 * (lin_base ** 0.5) # sqrt(t) works; use 0.3 for even denser points near 3
- Adjusting density: Use a smaller exponent (like 0.3) to make the density near 3 more pronounced, or a larger exponent (like 0.8) for a milder effect.
Method 3: Inverted Exponential Transformation
An inverted exponential function grows quickly at the start and asymptotes towards 3, creating smaller steps near the upper bound:
# Linear base sequence from 0 to 5 (adjust upper limit to control approach to 3) lin_base = np.linspace(0, 5, 100) # Inverted exponential to get dense at 3 exp_dense_at_3 = 3 * (1 - np.exp(-0.7 * lin_base))
- Tuning: Increase the multiplier (0.7) to make the sequence approach 3 faster, or decrease it to stretch out the approach.
Addressing Your Proposed Solution
Your code s = -1*(3*10**(-np.linspace(0,4,25))-1) simplifies to 1 - 3*10**(-t) where t ranges from 0 to 4. This produces values from -2 to ~0.9997, which doesn’t cover the full 0–3 range—likely a small typo. If you adjust it to target the 0–3 range, you’d end up with density near 0 (since exponential growth speeds up). The methods above are more direct for achieving density near 3.
内容的提问来源于stack exchange,提问作者Alejandro

