This paper presents the application of a mathematical algorithm based on the gradient method [1] to solve optimal power flows (OPF) in electrical microgrids with photovoltaic generation in order to improve the voltages profiles and consequently reduce the active power losses. The generation and storages devices were modeling by dynamic curves and the algorithm was implemented in a two electrical microgrids with distributed generation to demonstrate the effectiveness of the method using MATLAB Simulink simulations.