In: Computer Science
Can you please code in C the Lagrangian function.
If you have any questions please let me know.
#include <stdio.h>
// Defines a structure to store x and y = f(x)
struct Lagrangian
{
float x, y;
};// End of structure
// Function to to implement Lagrange's formula
// newPoint having new data point whose value needs to be
extracted
// numPoint represents the number of points
float lagrangianFunction(struct Lagrangian f[], float newPoint, int
numPoint)
{
float filanResult = 0;
// Loop variable
int c, d;
// Loops till number of points
for(c = 0; c < numPoint; c++)
{
// Compute each term result
float termValue = f[c].y;
// Loops till number of points to calculate termValue
for(d = 0; d < numPoint; d++)
// Checks if not diagonal
if (d != c)
// Calculates the term value based on the formula
termValue *= (newPoint - f[d].x) / (float)(f[c].x - f[d].x);
// Adds current term result to final result
filanResult += termValue;
}// End of for loop
// Returns the result
return filanResult;
}// End of function
// main function definition
int main()
{
float xValue;
int numPoint;
int c;
// Accepts the size
printf("\n Enter the number of the terms: ");
scanf("%d", &numPoint);
// Declares an array of object of size numPoint
struct Lagrangian f[numPoint];
printf("\n\n Enter values for variables x and y: \n");
// Loops till numPoint to accept x and y value
for(c = 0; c < numPoint; c++)
scanf("%f %f",&f[c].x, &f[c].y);
printf("\n\n Entered Values:\n");
for(c = 0; c < numPoint; c++)
printf(" %4.2f \t %4.2f \n", f[c].x, f[c].y);
printf(" \n\n Enter the value of the x to find the respective value
of y: ");
scanf("%f", &xValue);
// Calls the function to calculate and displays the return
result
printf("\n Value of f(%4.2f) is : %f", xValue,
lagrangianFunction(f, xValue, numPoint));
return 0;
}// End of main function
Sample Output:
Enter the number of the terms: 4
Enter values for variables x and y:
5 140
13 256
17 1125
23 2533
Entered Values:
5.00 140.00
13.00 256.00
17.00 1125.00
23.00 2533.00
Enter the value of the x to find the respective value of y: 12
Value of f(12.00) is : 93.762733