首页 > 代码库 > 拉格朗日函数c++

拉格朗日函数c++

  1. #include <iostream>
  2. using namespace std;
  3. //拉格朗日插值求解方程
  4. double * xs; //all input x
  5. double * ys; //all input y
  6. int n; //size
  7. //1.1275 1.1503 1.1735 1.1972
  8. //0.1191 0.13954 0.15932 0.17903
  9. //1.130
  10. void init()
  11. {
  12. cout << "please input n " << endl;
  13. cin >> n;
  14. xs = new double[n];
  15. ys = new double[n];
  16. //input x
  17. cout << "please input the x‘s value !" << endl;
  18. for(int i=0; i<n; i++)
  19. {
  20. cin >> xs[i];
  21. }
  22. //input y
  23. cout << "please input the y‘s value !" << endl;
  24. for(int i=0; i<n; i++)
  25. {
  26. cin >> ys[i];
  27. }
  28. }
  29. double everyItem(int num, double x)
  30. {
  31. double y = ys[num];
  32. double up = 1;
  33. double down = 1;
  34. for(int i=0; i<n; i++)
  35. {
  36. if(i != num)
  37. {
  38. up *= (x - xs[i]);
  39. down *= (xs[num] - xs[i]);
  40. }
  41. }
  42. return y*up/down;
  43. }
  44. double lagrange(double x)
  45. {
  46. double total = 0;
  47. for(int i=0; i<n; i++)
  48. {
  49. total = total + everyItem(i , x);
  50. }
  51. return total;
  52. }
  53. int main()
  54. {
  55. init();
  56. double input;
  57. cout << "please input you x !" <<endl;
  58. cin >> input;
  59. double result = lagrange(input);
  60. cout << "the result is " << result << endl;
  61. return 0;
  62. }



来自为知笔记(Wiz)


附件列表

     

    拉格朗日函数c++