Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created September 28, 2016 09:03
Show Gist options
  • Save lovasoa/a8f157805512eef1fe0abb6e08b0c23e to your computer and use it in GitHub Desktop.
Save lovasoa/a8f157805512eef1fe0abb6e08b0c23e to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <class T>
T lagrange(vector<T> xs, vector<T> ys, T x) {
T res = 0;
T mul;
size_t len = xs.size();
for (size_t i=0; i<len; i++) {
mul = 1;
for(size_t j=0; j<len; j++) {
if (i != j) {
mul *= (x-xs[j])/(xs[i]-xs[j]);
}
}
res += mul * ys[i];
}
}
int main()
{
vector<double> xs = {8, 9, 9.5, 10, 11};
vector<double> ys = {0,0,1,0,0};
double x;
while(true) {
cout << "x ? ";
cin >> x;
cout << "lagrange(" << x << ") = " << lagrange(xs, ys, x) << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment