fork download
  1. #include <array>
  2.  
  3. template<typename T, size_t N>
  4. std::array<T,N> newton(const std::array<T,N> &xs, const std::array<T,N> &ys)
  5. {
  6. std::array<T,N> as = ys;
  7. for (size_t k = 1; k < N; k++) {
  8. for (size_t j = N-1; j > k-1; j--) {
  9. as[j] = (as[j] - as[j-1]) / (xs[j] - xs[j-k]);
  10. }
  11. }
  12. return as;
  13. }
  14.  
  15. int main()
  16. {
  17. std::array<double, 4> xs = { 0.0, 1.0, -1.0, 2.0 };
  18. std::array<double, 4> ys = { 1.0, 5.0, -1.0, 17.0 }; // 1 + 2x + x^2 + x^3
  19. std::array<double, 4> as = newton(xs,ys); // 1 + 4x + 1x(x-1) + 1x(x-1)(x+1)
  20. printf("%g %g %g %g\n", as[0], as[1], as[2], as[3]);
  21. return 0;
  22. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
1 4 1 1