so, I got a code and I need to express my answers into 3 columns with x,y,a in program, by compiling I only get the calculation answers - 1 column with y value throughout the cycle [5] . How do I make it to a table with x, y, a columns and their values? Do I need another for cycle? Any suggestions are appreciated.
#include < iostream>
using namespace std;
float fy(float x, float a);
int main()
{
float a[5] = { -8, -6, -4, -2, 0 }
float y = 0;
int i = 0;
for (float x = -1; x <= 1; x += 0.5)
{
cout << fy(x, a[i]) << endl;
i++;
}
cin.get();
return 0;
}
float fy(float x, float a)
{
float y = 0;
if (sin(x)*a > 0)
y = sqrt(sin(x)*a);
else
cout << "no solution\n";
return y;
}
I guess what you want is something like this:
x y a
-1 2.59457 -8
-0.5 1.69604 -6
0 -nan -4
0.5 -nan -2
1 -nan 0
Right?
Following code should do the job:
#include <iostream>
#include <math.h>
using namespace std;
float fy(float x, float a);
int main() {
float a[5] = {-8, -6, -4, -2, 0};
float y = 0;
int i = 0;
cout << "x"
<< "\t"
<< "y"
<< "\t"
<< "a" << endl;
for (float x = -1; x <= 1; x += 0.5)
{
cout << x << "\t" << fy(x, a[i]) << "\t" << a[i] << endl;
i++;
}
cin.get();
return 0;
}
float fy(float x, float a) {
float y = 0;
if (sin(x) * a > 0)
y = sqrt(sin(x) * a);
else
y = sqrt(-1);
return y;
}
The problem in your code is that you only print the result of the function. So you neither print x nor you print the a[i] value. Check the replaced cout line and you'll see how to print the other values.
Related
I'm running a program that preforms a Euler Approximation of an Ordinary Differential Equation. The smaller the step size that is chosen, the more accurate the approximation is. I can get it to work for a set step size using this code:
#include <iostream>
using std::cout;
double f (double x, double t)
{
return t*x*x-t;
}
int main()
{
double x=0.0,t=0.0,t1=2.0;
int n=20;
double h = (t1-t) / double(n);
// ----- EULERS METHOD
for (int i=0; i<n; i++)
{
x += h*f(x,t);
t += h;
}
cout << h << " " << x << "\n";
}
So this code runs a Eulers approximation for n=20 which corresponds to a step size of 0.1 and outputs the step size along with the approximation for x(2). I want top know how to loop this code (for different values of n) so that it outputs this followed by increasingly smaller step sizes with corresponding approximations.
i.e an output something like this:
0.1 -0.972125
0.01 -0.964762
0.001 -0.9641
etc.
So I tried a for-loop inside a for-loop but its giving me a weird output of extreme values.
#include <iostream>
using std::cout;
double f (double x, double t)
{
return t*x*x-t;
}
int main()
{
double x=0.0,t=0.0,t1=2.0;
for (int n=20;n<40;n++)
{
double h = (t1-t)/n;
for (int i=0;i<n;i++)
{
x += h*f(x,t);
t += h;
}
cout << h << " " << x << "\n";
}
}
If I understand correctly, you want to execute that first piece of code inside your main function for different values of n. Then your problem is with the variables x, t and t1, which are set once before the loop and never reset. You want them inside your outer loop:
#include <iostream>
using std::cout;
double f( double x, double t )
{
return t * x * x - t;
}
int main()
{
for ( int n = 20; n < 40; n++ )
{
double x = 0.0, t = 0.0, t1 = 2.0;
double h = ( t1 - t ) / n;
for ( int i = 0; i < n; i++ )
{
x += h * f( x, t );
t += h;
}
cout << h << " " << x << "\n";
}
}
Using a function for this, makes it clearer:
#include <iostream>
using std::cout;
double f( double x, double t )
{
return t * x * x - t;
}
void eulers( const int n )
{
double x = 0.0, t = 0.0, t1 = 2.0;
double h = ( t1 - t ) / n;
for ( int i = 0; i < n; i++ )
{
x += h * f( x, t );
t += h;
}
cout << h << " " << x << "\n";
}
int main()
{
for ( int n = 20; n < 40; n++ )
{
eulers( n );
}
}
Hope this helps.
While I was writing a c++ program I stuck on a problem. In brief, my program input is one integer which is the number of coordinates that I have to input. And I have an algorithm that calculates the passed distance between all of the points. Here is my algorithm:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
const double PI = 3.14;
const double rightXLimit = 5;
const double leftXLimit = -5;
const double topYLimit = 2;
const double bottomYLimit = -2;
const int ARR_SIZE = 100;
bool IsPointInRules(double x, double y)
{
if ((x >= leftXLimit && x <= rightXLimit) && (y >= bottomYLimit && y <= topYLimit))
{
return true;
}
return false;
}
double checkLimitsAndDistCalc(double x, double y, double x1, double y1)
{
if (!(IsPointInRules(x, y) || IsPointInRules(x1, y1)))
{
return 0;
}
else if (IsPointInRules(x, y) && (!IsPointInRules(x1, y1)))
{
if (x1 <= leftXLimit)
{
x1 = leftXLimit;
}
if (x1 >= rightXLimit)
{
x1 = rightXLimit;
}
if (y1 <= bottomYLimit)
{
y1 = bottomYLimit;
}
if (y1 >= topYLimit)
{
y1 = topYLimit;
}
}
else if ((!IsPointInRules(x, y)) && IsPointInRules(x1, y1))
{
if (x <= leftXLimit)
{
x = leftXLimit;
}
if (x >= rightXLimit)
{
x = rightXLimit;
}
if (y <= bottomYLimit)
{
y = bottomYLimit;
}
if (y >= topYLimit)
{
y = topYLimit;
}
}
double distance = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2));
double result = ((PI * distance / 2) + distance) / 2;
//cout << setw(3) << x << setw(3) << y << setw(3) << x1 << setw(3) << y1 << " --> " << distance << " --> " << result << endl;
return result;
}
double calculateDistance(double* arrOne, double* arrTwo, int n)
{
double finalResult = 0;
for (int i = 0; i < n - 1; i++)
{
double getDistance = checkLimitsAndDistCalc(arrOne[i], arrTwo[i], arrOne[i + 1], arrTwo[i + 1]);
finalResult += getDistance;
}
return finalResult;
}
int main()
{
double coordsArrX[ARR_SIZE];
double coordsArrY[ARR_SIZE];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> coordsArrX[i];
cin >> coordsArrY[i];
}
cout << setprecision(3) << fixed << calculateDistance(coordsArrX, coordsArrY, n) << '\n';
}
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem. Here I tried some auto tests:
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem.
That is an incorrect conclusion. The output is same whether you enter the coordinates using what appears to be integers or floating point numbers.
The output obtained using
7
0 0
0 3
-2 4
-1 1
-3 -1
4 1
6 3
is the same as using
7
0.0 0.0
0.0 3.0
-2.0 4.0
-1.0 1.0
-3.0 -1.0
4.0 1.0
6.0 3.0
See the output from using floating point input at http://ideone.com/fxgbga.
It appears that there is something else in your program that is not working as you are expecting.
I am doing a former assignment in C++ and trying to figure out how to get correct ASCII X-Y plot.
So what's really happening is that user is given a menu which allows them to choose a particular trig function.All of the functions have range between [-4..6] for X and [-12...5] for Y.Next user will be allowed to select amount of graduations(or values between the restricted x and y range] and if they want to see resultant values or Bitmap.The final output will be in values/bitmap.I have pasted wolfram alpha link for the functions in comments.
What I have done is incremented each column in 2D output by product of 1/(graduation-1)(i.e. 1/3 if graduated value is 4) and column #.Once that product reaches 1,I am not getting correct output for the values.
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
void displayValues(double result[],int result_size,int graduationVal,double percentIncrease,int menuSelection){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
int division=0;
//Add Values into array until result-1 values
while(i < result_size){
//cout<<"Before j";
//Calculate all the horizontal axis values
for(int j=0; j< graduationVal;j++){
if(displaySelection==1){
//cout<<"In if";
if(menuSelection==1){
result[i]=sin(minX+(percentIncrease*j))*cos(minY+(percentIncrease*k));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
//cout<<sin(minX+(percentIncrease*j))<<"\n";
//cout<<cos(minY+(percentIncrease*k))<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==2){
result[i]=sin(minX+(percentIncrease*j))+pow(cos(minY+(percentIncrease*j)),2)-(minX+(percentIncrease*j))/(minY+(percentIncrease*k));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==3){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(0.5 *cos(minY+(percentIncrease*k)));
cout<<"\n Increase in value of x by "<<percentIncrease*j<<" ";
cout<<"Increase in value of y by "<<percentIncrease*k<<"\n";
cout<<result[i]<<" ";
}else if(menuSelection==4){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(minX+(percentIncrease*j)) * cos(3 * (minY+(percentIncrease*k)));
cout<<result[i]<<" ";
}
//cout<<"J is"<<j<<"\n";
//cout<<"K is"<<k<<"\n";
//cout<<"I is"<<i<<"\n";
}else{
if(menuSelection==1){
result[i]=sin(minX+(percentIncrease*j))*cos(minY+(percentIncrease*k));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==2){
result[i]=sin(minX+(percentIncrease*j))+pow(cos(minY+(percentIncrease*j)),2)-(minX+(percentIncrease*j))/(minY+(percentIncrease*k));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==3){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(0.5 *cos(minY+(percentIncrease*k)));
cout<<((result[i] > 0 )?"O":"X");
}else if(menuSelection==4){
result[i]=(0.5 * sin(minX+(percentIncrease*j)))+(minX+(percentIncrease*j)) * cos(3 * (minY+(percentIncrease*k)));
cout<<((result[i] > 0 )?"O":"X");
}
}//End display choice if
//Increment Array Index
i++;
//cout<<"Bottom of j";
}//End of j loop
cout<<"\n";
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=4+6;
double distanceFromMinMaxY=12+5;
int graduations=0;
// double precisionX;
// double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(x)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
// precisionX=distanceFromMinMaxX/graduations;
// precisionY=distanceFromMinMaxY/graduations;
displayValues(values,values_size,graduations,pctIncrease,menuChoice);
}
}
Edit:
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
double* calculateValues(double val[],int val_size,int graduationVal,double xPrecision,double yPrecision,int menuSelection){
/*int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;*/
int k=0;
int i=0;
//Add Values into array until result-1 values
while(i < val_size){
for(int j=0; j<graduationVal;j++){
if(menuSelection==1){
val[i]=sin(minX+(xPrecision*j))*cos(minY+(yPrecision*k));
}else if(menuSelection==2){
val[i]=sin(minX+(xPrecision*j))+pow(cos(minY+(xPrecision*j)),2)-(minX+(xPrecision*j))/(minY+(yPrecision*k));
}else if(menuSelection==3){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(0.5 *cos(minY+(yPrecision*k)));
}else if(menuSelection==4){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(minX+(xPrecision*j)) * cos(3 * (minY+(yPrecision*k)));
}
//Increment Array Index
i++;
}//End of j loop
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
return val;
}
void displayValues(double result[],int result_size,int numOfGraduations){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
while(i< result_size){
for(int j=0;j<numOfGraduations;j++){
if(displaySelection==1){
cout<<result[i]<<" ";
}else{
cout<<((result[i] > 0 )?"O":"X");
}
i++;
}
cout<<"\n";
}
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=4+6;
double distanceFromMinMaxY=12+5;
int graduations=0;
double precisionX;
double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(x)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
precisionX=distanceFromMinMaxX/graduations;
precisionY=distanceFromMinMaxY/graduations;
/*cout << "# of graduations: " << graduations << endl;
cout << "Precision: "<< endl;
cout << "x: " << precisionX << endl;
cout << "y: " << precisionY << endl;*/
calculateValues(values,values_size,graduations,precisionX,precisionY,menuChoice);
displayValues(values,values_size,graduations);
}
}
Edit:I am using gcc
This produces output similar to the screencap you linked (where the user chose option 2). The TextPlot2d function takes a lambda or functor which calculates the desired function, as well as two PlotRange structs for specifying how the x and y axes should be scaled. I also used different output characters because I had a hard time distinguishing 'X' vs. 'O'.
#include <iostream>
#include <cmath>
struct PlotRange {
double begin, end, count;
double get_step() const { return (end - begin) / count; }
};
template <typename F>
void TextPlot2d(F func, PlotRange range_x, PlotRange range_y) {
const auto step_x = range_x.get_step();
const auto step_y = range_y.get_step();
// multiply steps by iterated integer
// to avoid accumulation of error in x and y
for(int j = 0;; ++j) {
auto y = range_y.begin + step_y * j;
if(y >= range_y.end) break;
for(int i = 0;; ++i) {
auto x = range_x.begin + step_x * i;
if(x >= range_x.end) break;
auto z = func(x, y);
if(z != z) { std::cout << '?'; } // NaN outputs a '?'
else { std::cout << (z < 0 ? '#':'o'); }
}
std::cout << '\n';
}
}
int main() {
TextPlot2d(
[](double x, double y){ return std::sin(x) + std::cos(y/2)*std::cos(y/2) - x/y; },
{-4.0, 6.0, 40.0},
{-12.0, 5.0, 40.0}
);
}
Tada!
ooooooo######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
oooo###########ooooooooooooooooo######oo
ooo#############ooooooooooooooo#######oo
ooo#############ooooooooooooooo########o
oo##############ooooooooooooooo########o
ooo#############ooooooooooooooo########o
ooo#############oooooooooooooooo######oo
oooo###########oooooooooooooooooo####ooo
ooooo#########oooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooooo######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
oooooo#######ooooooooooooooooooooooooooo
ooooo#########oooooooooooooooooooooooooo
ooo############ooooooooooooooooooooooooo
oo#############ooooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
################oooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
###############ooooooooooooooooooooooooo
################oooooooooooooooooooooooo
oooooooooooooooooo######################
oooooooooooooooooooooo##################
oooooooooooooooooooooooo################
ooooooooooooooooooooooooo###############
ooooooooooo###ooooooooooo###############
ooooooooo#######ooooooooo###############
oooooooo########oooooooooo##############
ooooooo#########oooooooooo##############
ooooooo#########ooooooooooo#############
ooooooo########oooooooooooo#############
oooooooo######oooooooooooooo############
I finally got the output!!Appearantly function#2 was wrong and that's why I wasn't getting correct answer.
#include <iostream>
#include <cmath>
using namespace std;
double minX=-4;
double maxX=6;
double minY=-12;
double maxY=5;
void calculateValues(double val[],int val_size,int graduationVal,double xPrecision,double yPrecision,int menuSelection){
/*int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;*/
//double val[];
int k=0;
int i=0;
//Add Values into array until result-1 values
while(i < val_size){
for(int j=0; j<graduationVal;j++){
if(menuSelection==1){
val[i]=sin(minX+(xPrecision*j))*cos(minY+(yPrecision*k));
}else if(menuSelection==2){
val[i]=sin(minX+(xPrecision*j))+pow(cos((minY+(yPrecision*k))/2),2)-(minX+(xPrecision*j))/(minY+(yPrecision*k));
}else if(menuSelection==3){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(0.5 *cos(minY+(yPrecision*k)));
}else if(menuSelection==4){
val[i]=(0.5 * sin(minX+(xPrecision*j)))+(minX+(xPrecision*j)) * cos(3 * (minY+(yPrecision*k)));
}
//Go to next value in array
i++;
}//End of j loop
//Increment y-values
if(k<graduationVal){
k++;
}
}//End of While
}
void displayValues(double result[],int result_size,int numOfGraduations){
int displaySelection=0;
cerr<<"(0) Bitmap or (1) Values?";
cin>>displaySelection;
int k=0;
int i=0;
while(i< result_size){
for(int j=0;j<numOfGraduations;j++){
if(displaySelection==1){
cout<<result[i]<<" ";
}else{
cout<<((result[i] > 0 )?"O":"#");
}
i++;
}
cout<<"\n";
}
}
int main(){
int menuChoice=-1;
int displaychoice=0;
double distanceFromMinMaxX=maxX-minX;
double distanceFromMinMaxY=maxY-minY;
int graduations=0;
double precisionX;
double precisionY;
double pctIncrease;
while(menuChoice!=0){
cerr<<"Select your function\n";
cerr<<"1. sin(x)cos(y)\n";
cerr<<"2. sin(x)+cos^2(y/2)-x/y\n";
cerr<<"3. 1/2 sin(x) + 1/2 cos(y)\n";
cerr<<"4. 1/2 sin(x) + xcos(3y)\n";
cerr<<"0. Quit\n";
cin>>menuChoice;
if(menuChoice == 0){
return 0;
}
cerr<<"Number of graduations per axis: ";
cin>>graduations;
//pctIncrease=1/(double)(graduations - 1);
int values_size=graduations * graduations;
double values[values_size];
/*int yValues[graduationVal];*/
precisionX=(distanceFromMinMaxX)/graduations;
precisionY=(distanceFromMinMaxY)/graduations;
/*cout << "# of graduations: " << graduations << endl;
cout << "Precision: "<< endl;
cout << "x: " << precisionX << endl;
cout << "y: " << precisionY << endl;*/
calculateValues(values,values_size,graduations,precisionX,precisionY,menuChoice);
displayValues(values,values_size,graduations);
}
}
When I try to start my C++ program it stops with error "5.exe has stopped working". This program supposed to calculate how many tiles you need for pool, if number of tiles on one side is non-round number, add one row of tiles to it. P.S. Sorry for my bad English.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,z;
int a,b;
cout << "Insert dimensions of pool in metres: " << endl;
cin >> x >> y >> z;
cout << "Insert dimensions of tile in centimeters: " << endl;
cin >> a >> b;
a=a/100;
b=b/100;
int brx = 0, brzx = 0, bry = 0, brzy = 0, bxpod = 0, bypod = 0;
if (x%a == 0) {
brx = x / a;
}
else {
brx = x / a + 1;
}
if (z%b == 0) {
brzx = z / b;
}
else {
brzx = z / b + 1;
}
if (y%a == 0) {
bry = y / a;
}
else {
bry = y / a + 1;
}
if (z%b == 0) {
brzy = z / b;
}
else {
brzy = z / b + 1;
}
if (x%a == 0) {
bxpod = x / a;
}
else {
bxpod = x / a + 1;
}
if (y%b == 0) {
bypod = y / b;
}
else {
bypod = y / b + 1;
}
int s = (brx*brzx + bry*brzy) * 2 + bxpod*bypod;
cout << "You need " << s << "tiles." << endl;
system("pause");
return 0;
}
Using a debugger, you can easily find that you have a division by 0 in the following lline:
if (x%a == 0) {
brx = x / a;
}
You are doing an integer division on "a":
a = a / 100;
So if a is lower than 100, a will be 0. 10 / 100 = 0.1 = 0 when cast as int.
You should use double instead of int
Here is my code so far. There seems to be soemthing wrong since I keep getting an incorrect answer. I am writing in a text file that is formatted:
2
3.0 1.0
2 being the size of the array and then 3.0 and 1.0 being the coefficients. Hopefully I didnt miss much in my explanation. Any help would be greatly appreciated.
Thanks
double polyeval(double* polyarray, double x, int arraySize)
{
//int result = 0;
if(arraySize == 0)
{
return polyarray[arraySize];
}
//result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
return polyarray[arraySize-1]+ (x* (polyeval(polyarray,x,arraySize-1)));
//return result;
}
int main ()
{
int arraySize;
double x;
double *polyarray;
ifstream input;
input.open("polynomial.txt");
input >> arraySize;
polyarray = new double [arraySize];
for (int a = arraySize - 1; a >= 0; a--)
{
input >> polyarray[a];
}
cout << "For what value x would you like to evaluate?" << endl;
cin >> x;
cout << "Polynomial Evaluation: " << polyeval(polyarray, x, arraySize);
delete [] polyarray;
}
the idea that if i read in a text file of that format varying in size that it will solve for any value x given by the user
Jut taking a wild guess
for (int a = arraySize - 1; a >= 0; a--)
// ^^
{
input >> polyarray[a];
}
One error is here:
for (int a = arraySize - 1; a > 0; a--)
{ //^^should be a >=0
input >> polyarray[a];
}
You are missing some entry this way.
The recursive function should look like the following:
int polyeval(double* polyarray, double x, int arraySize)
{
if(arraySize == 1)
{
return polyarray[arraySize-1];
}
return x*(polyarray[arraySize-1]+polyeval(polyarray,x,arraySize-1));
}
The problem is mainly with the definition of the polynomial coefficients.
Your code assumes a polynomial on the form:
x( p(n) + x( p(n-1) + x( p(n-2) + ... x(p(1) + p(0)))..))
This line:
result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
Should become:
result += pow(x,arraySize)*polyarray[arraySize]+polyeval(polyarray,x,arraySize-1);
This way the polynomial is defined correctly as p(n)x^n + p(n-1)x^(n-1) ... + p1 x + p0
Couldn't work out exactly what you were trying to do, or why you were using recursion. So I whipped up a non-recursive version that seems to give the right results.
#include <iostream>
using namespace std;
double polyeval(const double* polyarray, double x, int arraySize) {
if(arraySize <= 0) { return 0; }
double value = 0;
const double * p = polyarray + (arraySize-1);
for(int i=0; i<arraySize; ++i) {
value *= x;
value += *p;
p--;
}
return value;
}
int main () {
const int arraySize = 3;
const double polyarrayA[3] = {0.0,0.0,1.0}; // 0 + 0 x + 1 x^2
const double polyarrayB[3] = {0.0,1.0,0.0}; // 0 + 1 x + 0 x^2
const double polyarrayC[3] = {1.0,0.0,0.0}; // 1 + 0 x + 0 x^2
cout << "Polynomial Evaluation A f(x) = " << polyeval(polyarrayA, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation B f(x) = " << polyeval(polyarrayB, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation C f(x) = " << polyeval(polyarrayC, 0.5, arraySize)<<std::endl;
}
You can see it running here:
http://ideone.com/HE4r6x