Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "stdlib.h"
- #include "math.h"
- float calculateX(float xFrom, float i, float step) {
- return xFrom + i * step;
- }
- float yFormula(float x) {
- return exp(-(x - 2) * (x - 2));
- }
- char* getQ(float x0, float h) {
- int bufLen = snprintf(0, 0, "(x - %f)/%f", x0, h);
- char* buf = (char*)malloc(bufLen + 1);
- snprintf(buf, bufLen + 1, "(x - %f)/%f", x0, h);
- return buf;
- }
- float calculateYDelta(float xFrom, float step, int power, int i) {
- if (power <= 1)
- return yFormula(calculateX(xFrom, i, step));
- else
- return calculateYDelta(xFrom, step, power - 1, i) - calculateYDelta(xFrom, step, power - 1, i + 1);
- }
- void printNewton1(float xFrom, float step, int n, char* q) {
- printf("P(x) = %f", calculateYDelta(xFrom, step, 0, 0));
- float fact = 1;
- for (int i = 1; i <= n; i++) {
- fact *= i;
- float yDelta = calculateYDelta(xFrom, step, i, 0);
- if (yDelta < 0) {
- yDelta *= -1;
- printf(" - ");
- }
- else
- printf(" + ");
- printf("%f(%s)", yDelta / fact, q);
- for (int j = 2; j <= i; j++)
- printf("(%s - %d)", q, j - 1);
- }
- }
- void printNewton2(float xFrom, float step, int n, char* q) {
- printf("P(x) = %f", calculateYDelta(xFrom, step, 0, n));
- float fact = 1;
- for (int i = 1; i <= n; i++) {
- fact *= i;
- float yDelta = calculateYDelta(xFrom, step, i, n - i);
- if (yDelta < 0) {
- yDelta *= -1;
- printf(" - ");
- }
- else
- printf(" + ");
- printf("%f(%s)", yDelta / fact, q);
- for (int j = 2; j <= i; j++)
- printf("(%s + %d)", q, j - 1);
- }
- }
- int main(int argc, char** argv) {
- float xFrom = 2;
- float xTo = 4;
- float step = 0.2;
- int n = (int)((xTo - xFrom) / step);
- char* q = getQ(xFrom, step);
- printNewton1(xFrom, step, n, q);
- free(q);
- printf("\n");
- q = getQ(xTo, step);
- printNewton2(xFrom, step, n, q);
- free(q);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement