分歧差异的方法

时间:2014-12-05 19:05:38

标签: c++

我的Divided Differences代码方法存在问题。实际上有两个问题如下:

  1. 如果我输入1或2个数据点,它正常工作,但是如果我 输入3个或更多数据点,结果将是错误的
  2. 我想要输出的形式如下:

    How many data points will be entered?: 5
    Enter x00: 1.0
    Enter y00: 0.7651977
    Enter x01: 1.3
    Enter y01: 0.6200860
    Enter x02: 1.6
    Enter y02: 0.4554022
    Enter x03: 1.9
    Enter y03: 0.2818186
    Enter x04: 2.2
    Enter y04: 0.1103623
    The interpolating polynomial is:
    P(x) =
        0.7651977
      - 0.4837057(x - 1.0)
      - 0.1087339(x - 1.0)(x - 1.3)
      + 0.0658784(x - 1.0)(x - 1.3)(x - 1.6)
      + 0.0018251(x - 1.0)(x - 1.3)(x - 1.6)(x - 1.9)
     Press any key to continue...
    
  3. 这是我的代码:

    #include <iostream>
    #include <vector>
    #include <stdexcept>
    using namespace std;
    
    double func(const std::vector< double > & a, const std::vector< double > & b, int i, int j){
        if ((i < 0) || (j < 0) || (i >= a.size()) || (j >= b.size()) || (i < j)) {
            return 0; // Ignore invalid arguments.
        }
        else if (i == j){
            return b[i];
        }
        else if (a[i] == a[j]) {
            return 0; // Avoid division by 0.
        }
        else if (i - j == 1){
            return (b[i] - b[j]) / (a[i] - a[j]);
        }
        else
            return (func(a, b, i, j - 1) - func(a, b, i - 1, j)) / (a[i] - a[j]);
    }
    
    int main()
    {
        int x;
    
        cout << "How many data points will be entered?:";
        cin >> x;
        std::vector< double > a;
        std::vector< double > b;
        for (int c = 0; c < x; c++){
            double v;
            cout << "Enter X0" << c << ":";
            cin >> v;
            a.push_back(v);
            cout << "Enter y0" << c << ":";
            cin >> v;
            b.push_back(v);
        }
    
    
        std::cout << std::endl;
        for (int i = 0; i < x; ++i)
            for (int j = 0; j < x; j = j + 2){
                try {
                double value = func(a, b, i, j);
    
                std::cout << "p(x): " << value << "(x-" << a[i] << ")" << std::endl;
                }
                catch (...) {
                    std::cout << "func( " << i << ", " << j << " ) = invalid " << std::endl;
                }
            }
        return 0;
    }
    

    注意:“我是C ++的初学者,我的英语很弱,所以如果你不明白这些问题,请告诉我解释一下,谢谢大家”

0 个答案:

没有答案