Gradient Calculation (task 101)

Back to Problem Solutions forum

Vladimir_V     2015-07-23 08:29:58

Hi! Just follow the intstruction from this task ang got nothing from it.

For Example: (JAVA)

        double X0Y0= Math.pow(X0-A, 2) + Math.pow(Y0-B, 2) + C*Math.exp(-(Math.pow(X0+A, 2))-Math.pow(Y0+B, 2));
        double X1Y0= Math.pow(X0+0.1-A, 2) + Math.pow(Y0-B, 2) + C*Math.exp(-(Math.pow(X0+0.1+A, 2))-Math.pow(Y0+B, 2));
        double X0Y1= Math.pow(X0-A, 2) + Math.pow(Y0+0.1-B, 2) + C*Math.exp(-(Math.pow(X0+A, 2))-Math.pow(Y0+0.1+B, 2));

        double gx=(X1Y0-X0Y0)/0.1;
        double gy=(X0Y1-X0Y0)/0.1;

        double rez=Math.atan2(gy, gx);


        and for A= -0.5,B=-0.4,c=7, x=0.3, y=0.2 I have rez = -1.445529755472373 radians but answer is 222 degree

        //It is the very first case from the problem Example

Any sugestions what is wrong with my calculus ?

Rodion (admin)     2015-07-23 10:42:23
User avatar

_> Any sugestions what is wrong with my calculus ? _

It is hard to tell for I get different answer with your calculation (probably, also incorrect) - see ideone yields about 0.7

Could you please refactor this example moving calculation of the function for given (x, y) into separate method so you can then write like

double x0y0 = func(x0, y0);
double x1y1 = func(x0 + dt, y0);
// etc...

Probably we'll be able to find out easier what is wrong either with your code or with my example :)

UPD Well, and now see, the result you get is the direction of the steepest accent, while gradient is the direction of the steepest descent - i.e. you additionaly need to flip the angle by 180 degrees.

Another important thing is that with input data like 0.2 and 0.3 the value of the step of 0.1 could be too large and may lead to significant errors so it is worth to try smaller values.

In other respects your code is correct and making these modifications I get the 222 after converting radians to degrees.

Please login and solve 5 problems to be able to post at forum