1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <iostream>
using namespace std;
const unsigned short N = 30; // max size of polynomials
double evaluate(double poly[], double x) {
for(int i=N-1; i; --i){
}
}
// degree of polynomial
int degreea(double a[]) {
for(int i=N-1; i; --i)
if (a[i])
return i;
return 0;
}
// degree of polynomial
int degreeb(double b[]) {
for(int i=N-1; i; --i)
if (b[i])
return i;
return 0;
}
void add(double a[], double b[], double result[]) {
for(int i=0; i<N; i++)
result[i] = a[i] + b[i];
}
void subtract(double a[], double b[], double result[]) {
for(int i=0; i<N; i++)
result[i] = a[i] - b[i];
}
void multiply(double a[], double b[], double result[]) {
for(int i=0; i<N; i++){
result[i] = 0;
for(int j = 0; j<N; j++) // needs to be fixed
if(i + j < N)
result[i+j] += a[i]*b[j];
}}
void differentiate(double a[], double result[]) {
}
// prints polynomials nicely
void print(double poly[]) {
bool first = true; // true for first non-zero coefficient
for (int i=N-1; i>=0; i--) {
if (!poly[i])
continue;
// print coefficient
if (i && poly[i] == 1) // special case for 1
cout << (first ? "" : " +");
else if (i && poly[i] == -1) // special case for -1
cout << (first ? "-" : " -");
else
cout << ' ' << (first ? noshowpos : showpos) << poly[i];
cout << noshowpos;
// print variable
if (i>0)
cout << "x";
// print power
if (i>1)
cout << '^' << i;
first = false;
}
if(first) // print 0 if all zeros
cout << 0;
}
int main() {
double a[N] = {12, 1, 0, -32.5, 0, 1}; // The first polynomial
cout << endl << "Evaluation:" << endl;
double x=-7.3;
cout << "If x = " << x << ", then ";
print(a);
cout << " = " << evaluate(a, x) << endl;
double b[N] = {1, 1, -1}; // The second polynomial
double c[N];
cout << endl << "Addition:" << endl;
add(a,b,c);
cout << '(';
print(a);
cout << ") + (";
print(b);
cout << ") = ";
print(c);
cout << endl;
cout << endl << "Subtraction:" << endl;
subtract(a,b,c);
cout << '(';
print(a);
cout << ") - (";
print(b);
cout << ") = ";
print(c);
cout << endl;
cout << endl << "Multiplication:" << endl;
multiply(a,b,c);
cout << '(';
print(a);
cout << ") * (";
print(b);
cout << ") = ";
print(c);
cout << endl;
cout << endl << "Differentiation:" << endl;
cout << "The derivative of (";
print(a);
cout << ") is (";
differentiate(a,c);
print(c);
cout << ')' << endl;
cout << "Its second derivative is (";
differentiate(c,c);
print(c);
cout << ')' << endl;
}
|