Advertisement
NyanCoder

Newton.c

May 15th, 2022
838
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "math.h"
  4.  
  5. float calculateX(float xFrom, float i, float step) {
  6.     return xFrom + i * step;
  7. }
  8. float yFormula(float x) {
  9.     return exp(-(x - 2) * (x - 2));
  10. }
  11.  
  12. char* getQ(float x0, float h) {
  13.     int bufLen = snprintf(0, 0, "(x - %f)/%f", x0, h);
  14.     char* buf = (char*)malloc(bufLen + 1);
  15.     snprintf(buf, bufLen + 1, "(x - %f)/%f", x0, h);
  16.     return buf;
  17. }
  18.  
  19. float calculateYDelta(float xFrom, float step, int power, int i) {
  20.     if (power <= 1)
  21.         return yFormula(calculateX(xFrom, i, step));
  22.     else
  23.         return calculateYDelta(xFrom, step, power - 1, i) - calculateYDelta(xFrom, step, power - 1, i + 1);
  24. }
  25.  
  26. void printNewton1(float xFrom, float step, int n, char* q) {
  27.     printf("P(x) = %f", calculateYDelta(xFrom, step, 0, 0));
  28.     float fact = 1;
  29.     for (int i = 1; i <= n; i++) {
  30.         fact *= i;
  31.         float yDelta = calculateYDelta(xFrom, step, i, 0);
  32.         if (yDelta < 0) {
  33.             yDelta *= -1;
  34.             printf(" - ");
  35.         }
  36.         else
  37.             printf(" + ");
  38.         printf("%f(%s)", yDelta / fact, q);
  39.         for (int j = 2; j <= i; j++)
  40.             printf("(%s - %d)", q, j - 1);
  41.     }
  42. }
  43.  
  44. void printNewton2(float xFrom, float step, int n, char* q) {
  45.     printf("P(x) = %f", calculateYDelta(xFrom, step, 0, n));
  46.     float fact = 1;
  47.     for (int i = 1; i <= n; i++) {
  48.         fact *= i;
  49.         float yDelta = calculateYDelta(xFrom, step, i, n - i);
  50.         if (yDelta < 0) {
  51.             yDelta *= -1;
  52.             printf(" - ");
  53.         }
  54.         else
  55.             printf(" + ");
  56.         printf("%f(%s)", yDelta / fact, q);
  57.         for (int j = 2; j <= i; j++)
  58.             printf("(%s + %d)", q, j - 1);
  59.     }
  60. }
  61.  
  62. int main(int argc, char** argv) {
  63.     float xFrom = 2;
  64.     float xTo = 4;
  65.     float step = 0.2;
  66.  
  67.     int n = (int)((xTo - xFrom) / step);
  68.  
  69.     char* q = getQ(xFrom, step);
  70.     printNewton1(xFrom, step, n, q);
  71.     free(q);
  72.  
  73.     printf("\n");
  74.  
  75.     q = getQ(xTo, step);
  76.     printNewton2(xFrom, step, n, q);
  77.     free(q);
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement