Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. using namespace std;
  6.  
  7. #define n 2
  8.  
  9.  
  10. double f(double *x)
  11. {
  12. int i;
  13. double output=0;
  14. for (i=0; i<n;i++)
  15. {
  16. output +=(x[i]-2)*(x[i]-2);
  17. }
  18. return output;
  19. }
  20. int coorddescent (double pas, double alfa, double epsilon, double *x)
  21. {
  22. int i;
  23. float out;
  24. int steps=0;
  25. double dist = 10*epsilon;
  26. int directie=1;
  27. int x1[n];
  28. int x2[n];
  29. while (dist>=epsilon)
  30. {
  31.  
  32. for(i=0;i<n;i++)
  33. {
  34. x1[i]=x[i];
  35. out=f(x);
  36. directie=1;
  37. x[i]=x[i]+directie*pas;
  38. steps++;
  39. if (out<f(x))
  40. {
  41. directie= -1;
  42. x[i]=x[i]+directie*pas;
  43. steps++;
  44. }
  45. printf ("out=%f, f=%f, directie=%d\n",out, f(x),directie);
  46. while (out >= f(x))
  47. {
  48. out= f(x);
  49. x[i]=x[i]+directie*pas;
  50. steps++;
  51. printf ("out=%f, f=%f, dist=%f\n",out, f(x),dist);
  52. }
  53. x2[i] = x[i];
  54. printf("x[%d]=%f\n",i,x[i]);
  55.  
  56. }
  57. for(int j=0;j<n;j++)
  58. {
  59. dist += (x1[j]-x2[j])*(x1[j]-x2[j]);
  60. }
  61. dist = sqrt(dist);
  62. pas=pas*alfa;
  63. printf("pas=%f\n\n",pas);
  64. dist = 0;
  65.  
  66. }
  67.  
  68. return steps;
  69. }
  70.  
  71. int main ()
  72. {
  73. int i;
  74. double pas=1;
  75. double alfa=0.5;
  76. double epsilon=0.0001;
  77. double x[n]={10.5 , 10};
  78. printf("steps= %d\n ", coorddescent(pas, alfa,epsilon,x));
  79. for (i=0; i<n;i++)
  80. {
  81. printf("x[%d] =%2.5f\n",i , x[i]);
  82. }
  83.  
  84. system("pause");
  85. return 0;
  86.  
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement