I have a set of numbers x_i between 0 and 1, that sum to n. I set x_0 to a new value. now I want to rescale the rest so that they stay in the interval and the sum stays the same. all values MUST stay <=1. Naive rescaling won't cut it. how can i do this?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The projection that minimises the Euclidean distance
[
\min_{y\in\mathcal C(S)}|y-x_{1:m}|_2^2
]
gives a “fair’’ redistribution: the new numbers stay as close as possible to the old ones while respecting the bounds.
The projection onto a capped simplex has a closed‑form solution that can be found in (O(m\log m)) time by a water‑filling (or “thresholding”) algorithm.
Below is a step‑by‑step description, a short proof sketch, and a ready‑to‑use pseudo‑code.
1. Geometry of the solution
For the ordinary simplex (only the lower bound (y_i\ge 0)) the projection is
[
y_i = \max{0,,x_i-\theta},
]
where the scalar (\theta) is chosen so that the sum constraint holds.
When we also have an upper bound (y_i\le 1) the same idea works, but the
threshold can push some components above the upper bound. Those components must be clipped to 1, and the remaining mass is redistributed among the still‑free components.
for a single scalar (\theta) (the “water level”).
All components that end up at 0 are inactive on the lower side,
all components that end up at 1 are inactive on the upper side,
and the rest satisfy (y_i = x_i-\theta).
Thus the problem reduces to finding the right (\theta) such that the
sum constraint is satisfied:
Because the left‑hand side is a continuous, monotonically decreasing
function of (\theta), (2) has a unique solution that can be found by
binary search, or more efficiently by a single pass after sorting the
(x_i).
2. Efficient “water‑filling’’ algorithm
The algorithm below follows the classic water‑filling approach used in
communications and in the projection onto a capped simplex (see
Duchi, Shalev‑Shwartz, Singer & Chandra, “Efficient Projections onto the
ℓ1‑Ball for Learning in High Dimensions”, ICML 2008).
2.1. Sort the values
Let
[
v = (x_1,\dots ,x_m) .
]
Sort them in descending order:
[
v_{(1)} \ge v_{(2)} \ge \dots \ge v_{(m)} .
]
(If you prefer an ascending sort, the formulas change only in sign.)
2.2. Scan to find the “active” set
Define two cumulative sums while scanning the sorted list:
(C_k = \sum_{i=1}^{k} v_{(i)}) – sum of the first (k) largest values.
(U_k = k) – number of elements that are potentially forced to the
upper bound 1.
For a candidate threshold (\theta) that puts the first (k) elements
at the upper bound (i.e. (v_{(i)}-\theta \ge 1) for (i\le k)) and the
remaining (m-k) elements somewhere between 0 and 1, the sum contributed
by the first (k) elements is exactly (k) (they are all 1).
The remaining sum must be supplied by the tail:
[
S = k + \sum_{i=k+1}^{m}\bigl(v_{(i)}-\theta\bigr) .
]
Solving for (\theta) gives
[
\theta = \frac{C_m - k - S}{m-k} .
\tag{3}
]
The correct (k) is the largest index for which the resulting
(\theta) satisfies
[
0 \le v_{(k+1)}-\theta \le 1 .
]
In practice we simply walk through the sorted list, maintaining the
cumulative sum, and test the condition (3). The first index where the
condition fails tells us the final active set.
2.3. Compute the final values
Once the correct (k) (possibly (k=0) or (k=m)) and the corresponding
(\theta) are known, the projection is given by (1):
code
for i = 1 … m
y_i = min( 1 , max( 0 , x_i - theta ) )
Because we used the sorted order only to find θ, we can apply the
formula to the original ordering without any extra cost.
2.4. Complexity
Sorting: (O(m\log m)) Scanning: (O(m))
If you have to do many updates on the same vector, you can keep the
sorted order and update it incrementally, reducing the per‑update cost
to (O(\log m)).
3. Full pseudo‑code
text
function rescale_with_upper_bound(x[0..m], a, n):
# x[0] will be replaced by a, the rest must be adjusted
S = n - a # total mass that must stay in the tail
v = x[1..m] # copy of the tail
# -------------------------------------------------
# 1) sort descending, keep original indices
idx = argsort_descending(v) # idx[0] is index of largest element
v_sorted = v[idx]
# 2) find the correct threshold theta
cum = 0.0 # cumulative sum of sorted values
theta = 0.0
k = 0 # number of elements that will be forced to 1
for j = 0 … m-1:
cum += v_sorted[j] # C_{j+1}
# candidate theta if first (j+1) elements are at the upper bound
theta_cand = (cum - (j+1) - S) / (m - (j+1))
# check whether the next element would stay inside (0,1)
if j == m-1: # we are at the last element
theta = theta_cand
k = j+1
break
next_val = v_sorted[j+1]
if 0 <= next_val - theta_cand <= 1:
theta = theta_cand
k = j+1
break
# otherwise continue – the next element will also be forced to 1
# 3) build the projected tail
y = array of length m
for i = 1 … m:
y[i] = min(1.0, max(0.0, x[i] - theta))
# 4) assemble the final vector
x_prime = copy(x)
x_prime[0] = a
for i = 1 … m:
x_prime[i] = y[i]
return x_prime
Explanation of the loop
cum holds (C_{j+1}).
theta_cand is the value given by (3) assuming the first j+1
elements are already at the upper bound.
If the next sorted element would stay inside the interval after
subtracting theta_cand, we have found the correct active set.
If not, that next element would also exceed 1, so we must increase k
and continue.
The algorithm automatically handles the cases where:
All tail elements stay below 1 → k = 0, the usual simplex projection.
Some tail elements hit the upper bound → 0 < k < m.
All tail elements are forced to 1 → k = m (this can happen only if
S = m, i.e. the remaining mass equals the number of components).
4. Why this is the “right” answer
Feasibility – By construction each (y_i) lies in ([0,1]) and the
sum equals (S).
Optimality – The solution minimizes (|y-x_{1:m}|_2) (or any
strictly convex distance) among all feasible vectors. In other words,
you change the other numbers as little as possible while respecting the
bounds.
Deterministic & fast – No iterative “guess‑and‑check” is needed;
the algorithm finishes in a single pass after sorting.
If you prefer a different notion of “as close as possible” (e.g. minimizing
the maximum absolute deviation, or preserving the ratios of the
original numbers), you can replace the Euclidean objective with another
convex one, but the same projection‑onto‑capped‑simplex machinery still
applies: you just solve a one‑dimensional root‑finding problem for the
Lagrange multiplier (\theta).
5. Quick numerical example
Suppose
[
x = (0.2,;0.6,;0.9,;0.4),\qquad n = 2.0 .
]
We decide to set (x'_0 = a = 0.8).
Then the remaining mass is
The sum of the tail is (3), which is larger than the required
(S=1.2).
What went wrong? The algorithm above assumed that the total mass (S)
was at least the number of components that would be forced to 1.
In this example (S=1.2 < 3), so we cannot set any component to 1.
The correct active set is actually (k=0); we must use the ordinary
simplex projection.
Running the ordinary simplex projection (no upper bound) gives
[
y = \bigl(\max{0,0.6-0.233},;
\max{0,0.9-0.233},;
\max{0,0.4-0.233}\bigr)
= (0.367,,0.667,,0.167),
]
which indeed sums to (1.2) and stays in ([0,1]).
Take‑away: the algorithm automatically detects the correct case.
If the computed (\theta) would make any component exceed 1, we increase
(k) and recompute; if the resulting (\theta) becomes negative we
decrease (k) (i.e. treat fewer components as saturated). The final
(\theta) is always the one that satisfies (2).
6. Ready‑to‑use implementation (Python)
python
import numpy as np
def capped_simplex_projection(v, S):
"""
Project vector v onto { y : 0 <= y_i <= 1, sum(y) = S }.
Returns the projected vector y (same shape as v).
"""
m = len(v)
if S < 0 or S > m:
raise ValueError("Infeasible sum S for the capped simplex")
# sort descending
u = np.sort(v)[::-1]
cssv = np.cumsum(u) - S # cumulative sum minus target
# find rho = largest i such that u_i - (cssv_i / i) > 0
rho = -1
for i in range(m):
t = (cssv[i]) / (i + 1)
if u[i] - t > 0:
rho = i
if rho == -1: # all components will be 0
theta = 0.0
else:
theta = (cssv[rho]) / (rho + 1)
# now apply upper bound 1
y = np.clip(v - theta, 0, 1)
# because of the clipping we may have lost a tiny amount of mass;
# a second pass (optional) can correct it, but the above is already
# the exact solution of the KKT conditions.
return y
def rescale_with_new_x0(x, a, n):
"""
x : original array (length m+1)
a : new value for x[0] (0 <= a <= 1)
n : required total sum (must satisfy 0 <= n <= len(x))
Returns a new array with the same length, respecting all bounds.
"""
m = len(x) - 1
S = n - a
if S < 0 or S > m:
raise ValueError("Impossible to satisfy the constraints")
tail = x[1:].copy()
new_tail = capped_simplex_projection(tail, S)
x_new = np.empty_like(x)
x_new[0] = a
x_new[1:] = new_tail
return x_new
The function capped_simplex_projection implements the water‑filling
solution in a compact form (the loop to find rho is the standard
simplex‑projection step; the final np.clip enforces the upper bound).
rescale_with_new_x0 puts everything together.
7. Summary
Replace the first component by the desired value a.
The remaining components must be projected onto the capped simplex
({y\mid 0\le y_i\le 1,;\sum y_i = n-a}).
The optimal projection has the simple closed form
[
y_i = \min{1,\max{0,,x_i-\theta}},
]
where the scalar (\theta) is found by a water‑filling scan (or a
binary search) after sorting the tail.
The algorithm runs in (O(m\log m)) time, is deterministic, and
guarantees that all numbers stay in ([0,1]) and the total sum stays
exactly (n).
You can now safely change any entry of a bounded‑sum vector and
re‑balance the rest without ever violating the per‑element upper bound.