calculating gradient