Lagrange Function C + +

Source: Internet
Author: User

  
 
  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. }



From for notes (Wiz)

List of attachments

    Lagrange Function C + +

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.