Improved gradient function by utilizing least squares method. Possible performance bottleneck at higher sizes