import numpy as np def check_margin(): # q(x)=x^2/2, xdot=u+w, |w|<=wbar: max_w grad(q)w=wbar|x|. x=.6; ws=np.linspace(0,.8,9) predicted=ws*abs(x) observed=np.array([max(x*w for w in (-w, w)) for w in ws]) slope=np.polyfit(ws,observed,1)[0] return {'predicted_slope':float(abs(x)), 'observed_slope':float(slope), 'max_abs_error':float(np.max(abs(predicted-observed))), 'confirmed':bool(np.max(abs(predicted-observed))<1e-10)} def check_projection(): # Scalar QP min .5(u-u0)^2 subject to u<=b, u in [-1,1]. u0=.8; b=.25; u=max(-1.,min(1.,min(u0,b))) return {'u0':u0,'bound':b,'projected':u,'constraint_residual':float(u-b), 'confirmed':bool(u<=b+1e-12)} if __name__=='__main__': import json out={'margin_scaling':check_margin(),'scalar_qp_projection':check_projection()} print(json.dumps(out,indent=2))