使用 C++ 计算上限和下限

时间:2021-03-30 07:28:26

标签: c++ limit

我正在编写一个基于常量数组 a 和指数数组 b 输出多项式的类,这样就生成了这个方程:

enter image description here

然而,这个方程没有 f(0) 的解,但可以使用两边的极限来计算(假设它们相等)。你怎么能用 C++ 实现这个,因为我完全不知道从哪里开始。

编辑


感谢您的评论(我还不能评论)。我的编码确实有点太快了,但我还是想自己编写函数,因为这正是我想学习的东西。

2 个答案:

答案 0 :(得分:2)

通常,f(0) 的限制仅取决于归一化多项式的最小指数。

归一化多项式(我称之为)是多项式,其中所有属于重复 a 值的 b 值都相加,只有非零 a值被保留。

  1. 如果最小指数大于 0,则 f(0) = 0
  2. 如果最小指数为 0,则对应的 a 值是 f(0) 的结果
  3. 如果最小指数小于 0,则限制为正无穷大和/或负无穷大
    • 即使是最小的指数也意味着上限和下限同向
    • 奇数最小指数表示上限和下限相反

此方法仅适用于整数 b。至少我没有调查其他案例的所有细节。

#include <iostream>
#include <limits>
#include <map>

using namespace std;

double f0(int* a, int* b, int n);

int main()
{
    int a[] = {2, 4, 6, -2, 5, -4};
    int b[] = {2, 1, -1, -1, 0, -1};
    // number of values in array a and b
    int n = 6;
    
    double result = f0(a, b, n);
    
    cout << "f(0) = " << result << endl;
    
    return 0;
}

double f0(int* a, int* b, int n)
{
    map<int, int> exponents;
    
    for (int i = 0; i < n; ++i)
    {
        exponents[b[i]] += a[i];
        // debug printing intermediate sums per exponent
        cout << b[i] << ": " << exponents[b[i]] << endl;
    }
    
    int minExp = 0;
    
    for (auto it = exponents.begin(); it != exponents.end(); ++it)
    {
        if (it->second != 0 && it->first < minExp)
        {
            minExp = it->first;
        }
    }
    
    // no negative exponent. f(0) is defined by 0 exponents
    if (minExp == 0) return exponents[0];
    
    // minimum exponent is even => positive or negative infinity limit
    if (minExp % 2 == 0)
    {
        return exponents[minExp] > 0
            ? numeric_limits<double>::infinity()
            : -numeric_limits<double>::infinity();
    }
    
    // minimum exponent is odd => f(0) limits approach both positive AND negative infinity
    return numeric_limits<double>::quiet_NaN();
}

答案 1 :(得分:0)

希望这段代码对你有帮助

#include <iostream>
#include <math.h>

double F(int X)
{
    const int numOfSentence = 3;
    double a[numOfSentence] = { 2,4,6 };
    double b[numOfSentence] = { 1,2,-1 };

    double result = 0;
    for (int i = 0; i < numOfSentence; i++)
    {
        result += a[i] * pow(X, b[i]);
    }

    return result;
}

int main()
{
    std::cout << F(2);
}