Skip to content
DeepForgeby svx
All problems
MediumOptimizationop-287

Projection Onto L2 Ball

Problem

The Euclidean projection onto the ball of radius r keeps points already inside and rescales outside points by r / ||x||.

Given the point and the radius r > 0, return the projection. Return the input copy when the norm is zero.

Hint

Only the radial component scales; direction is preserved.

Test cases

case 1
in: [[1,0],2]
expected: [1,0]
case 2
in: [[3,4],2]
expected: [1.2000000000000002,1.6]
case 3
in: [[0,0],1]
expected: [0,0]
Starter codePython
def projection_onto_l2_ball(x, radius):
    # Your code here
    pass

3 test cases · run your code against them in the editor