Skip to content

Instantly share code, notes, and snippets.

@ikariiin
Created June 1, 2022 11:49
Show Gist options
  • Save ikariiin/1c3863036b9cd7dd264377a80d5d0171 to your computer and use it in GitHub Desktop.
Save ikariiin/1c3863036b9cd7dd264377a80d5d0171 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <math.h>
float lagrange(float x, int n, float xi[], float yi[])
{
float sum = 0;
for (int i = 0; i < n; i++)
{
float product = 1;
for (int j = 0; j < n; j++)
{
if (i != j)
{
product *= (x - xi[j]) / (xi[i] - xi[j]);
}
}
sum += product * yi[i];
}
return sum;
}
int main()
{
float x;
int n;
float xi[10], yi[10];
printf("Enter the value of n: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter the value of x(%d): ", i + 1);
scanf("%f", &xi[i]);
printf("Enter the value of y(%d): ", i + 1);
scanf("%f", &yi[i]);
}
printf("Enter the value of x: ");
scanf("%f", &x);
printf("The value of f(x) is %.4f\n", lagrange(x, n, xi, yi));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment