|
-
July 16th, 2010, 07:16 PM
#1
beginner wanting criticism
I'm teaching myself c++ and giving myself random stuff to program. This program works, mostly, but I know for a fact that it could have been done much much better. This program is basically Newton's Method http://en.wikipedia.org/wiki/Newtons_method for polynomials. I'm mainly seeking out criticism on this code because I know it isn't the best quality. I know I shouldn't use global variables and I should do comments, but ya...
Code:
#include <iostream>
#include "math.h"
using namespace std;
double a;
double b;
double c;
double d;
double e;
double f;
double linearsolver(double slope, double x_coordinate, double y_coordinate)
{
double solution = 0 - y_coordinate;
solution = solution/slope;
solution = solution + x_coordinate;
return solution;
}
double equation(double x)
{
double result;
result=a*x*x*x*x*x+b*x*x*x*x+c*x*x*x+d*x*x+e*x+f;
return result;
}
double differentiation(double number_diff_at)
{
double i=0.001;
double result,neg_result;
do
{
result=(equation(number_diff_at+i)-equation(number_diff_at)/i;
neg_result=(equation(number_diff_at-i)-equation(number_diff_at))/(-i);
if(floor(result-neg_result)!=0)
{
i=i*i;
}
}while(floor(result-neg_result)!=0);
double deriv_result=(result+neg_result)/2;
return deriv_result;
}
double newtons_method(double initialguess, int iterations)
{
double x=initialguess;
double y,slope,result;
int n;
for(n=iterations;n!=0;n--)
{
slope=differentiation(x);
y=equation(x);
result=linearsolver(slope,x,y);
x=result;
}
return result;
}
int main()
{
double initialguess, result;
int n;
cout<<"a: ";
cin>>a;
cout<<"b: ";
cin>>b;
cout<<"c: ";
cin>>c;
cout<<"d: ";
cin>>d;
cout<<"e: ";
cin>>e;
cout<<"f: ";
cin>>f;
cout<<"\ninitial guess: ";
cin>>initialguess;
cout<<"iterations: ";
cin>>n;
result=newtons_method(initialguess,n);
cout<<"\nsolution is: "<<result<<"\n";
cin>>n;
return 0;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|