Untitled
plain_text
2 months ago
1.5 kB
1
Indexable
Never
#include <stdio.h> // Function to calculate the derivative using Newton divided difference double newtonDividedDifference(double x[], double y[], int n, double target) { double result = 0.0; // Calculate divided differences double dividedDiffs[n][n]; for (int i = 0; i < n; i++) { dividedDiffs[i][0] = y[i]; } for (int j = 1; j < n; j++) { for (int i = 0; i < n - j; i++) { dividedDiffs[i][j] = (dividedDiffs[i + 1][j - 1] - dividedDiffs[i][j - 1]) / (x[i + j] - x[i]); } } // Calculate the derivative value double xProduct = 1.0; for (int i = 0; i < n; i++) { result += dividedDiffs[0][i] * xProduct; xProduct *= (target - x[i]); } return result; } int main() { int n; // Number of data points printf("Enter the number of data points: "); scanf("%d", &n); double x[n], y[n]; // Arrays to store data points printf("Enter the data points (x y):\n"); for (int i = 0; i < n; i++) { scanf("%lf %lf", &x[i], &y[i]); } double target; // The point at which derivative is to be calculated printf("Enter the value of x for which you want to calculate the derivative: "); scanf("%lf", &target); double derivative = newtonDividedDifference(x, y, n, target); printf("The derivative at x = %.2lf is: %.4lf\n", target, derivative); return 0; }