Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- class Lagrange{
- double **diff_table;
- int n;
- double *x, *y;
- double x_unknown;
- double y_at_x_un;
- public:
- Lagrange(int);
- ~Lagrange();
- void input();
- void calcDiffTable();
- void calcY();
- void display();
- };
- Lagrange::Lagrange(int n){
- Lagrange::n = n;
- x = new double[n];
- y = new double[n];
- diff_table = new double*[n];
- for(int i = 0; i < n; i++){
- diff_table[i] = new double[n];
- }
- }
- Lagrange::~Lagrange(){
- delete[] x;
- delete[] y;
- for(int i = 0; i < n; i++){
- delete[] diff_table[i];
- }
- }
- void Lagrange::input(){
- for(int i = 0; i < n; i++){
- cout << "x[" << i << "] = ";
- cin >> x[i];
- cout << "y[" << i << "] = ";
- cin >> y[i];
- }
- cout << "Enter unknown x: ";
- cin >> x_unknown;
- }
- void Lagrange::calcDiffTable(){
- // Setting the diagonals
- for(int i = 0; i < n; i++){
- diff_table[i][i] = x_unknown - x[i];
- }
- // Setting rest of the elements
- for(int i = 0; i < n; i++){
- for(int j = 0; j < n; j++){
- if(i != j){
- diff_table[i][j] = x[i] - x[j];
- }
- }
- }
- }
- void Lagrange::calcY(){
- double l_i;
- y_at_x_un = 0;
- double numerator;
- double denominator;
- for(int i = 0; i < n; i++){
- numerator = 1;
- denominator = 1;
- for(int j = 0; j < n; j++){
- if(i != j){
- numerator = numerator * diff_table[j][j];
- denominator = denominator * diff_table[i][j];
- }
- }
- l_i = numerator / denominator;
- y_at_x_un += (l_i * y[i]);
- }
- }
- void Lagrange::display(){
- calcDiffTable();
- cout << "\nElements in the Lagranges Difference Table" << endl;
- for(int i = 0; i < n; i++){
- for(int j = 0; j < n; j++){
- cout << diff_table[i][j] << "\t";
- }
- cout << endl;
- }
- cout << endl;
- calcY();
- cout << "Unknown y-value = " << y_at_x_un << endl;
- }
- int main() {
- system("cls");
- cout << "Enter the number of points: ";
- int n;
- cin >> n;
- Lagrange L(n);
- L.input();
- L.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment