In this paper, an optimization-based control algorithm for the compensation of steady-state load under distorted supply voltages is presented. For balanced and sinusoidal supply voltages, load compensation using shunt active filter produces perfect harmonic cancellation (PHC) and unity power factor (UPF) source currents. However, when the supply voltages are distorted, compensation for PHC will not provide UPF, as the harmonics in the supply voltages are not utilized for delivering the average power. In the same way, to achieve UPF source currents, the compensated source currents should have the same harmonics, unbalance, shape, and be in phase with the respective supply voltages, thereby violating the perfect harmonic cancellation objective. Hence, there should be an optimal operation between these two important compensation characteristics. The optimization-based control algorithm presented in this paper gives the best power factor while satisfying the constraints such as total harmonic distortion limits and average power balance of source currents. It is also flexible to adopt different compensation characteristics based upon the supply voltage conditions. MATLAB and its optimization toolbox are used for simulation studies and solving the nonlinear optimization problem, respectively. The algorithm is validated by using a prototype of digital signal processor (TMS320F2812PGFA)-based shunt active power filter. Detailed experimental results are presented.Index Terms-Active power filter (APF), digital signal processor (DSP), load compensation, optimization, perfect harmonic cancellation, unity power factor.