Reputation: 149
I am writing a class that spits out polynomials based on a constants array a and exponent array b, such that this equation is generated:
However, this equation does not have a solution for f(0), but it can be calculated using the limits from both sides (given that they are equal). How could you implement this in C++, since I do absolutely not know where to start.
EDIT
Thanks for the comments (I cannot comment yet). I was indeed a bit too fast with the coding, but I do nevertheless want to write the function myself, because that is exactly the thing I want to learn.
Upvotes: 0
Views: 1219
Reputation: 13458
Generally, the limits for f(0)
will depend only on the smallest exponent of the normalized polynom.
The normalized polynom (as I call it) is the polynom, where all a
values, that belong to a repeated b
value are added up and only the non-zero a
values are kept.
f(0) = 0
a
value is the result for f(0)
This approach only works for whole numbers b
. At least I didn't investigate all the details for other cases.
#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();
}
Upvotes: 1
Reputation: 47
I hope this code helps you
#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);
}
Upvotes: 0