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
|
#include <iostream>
#include <cmath>
#include <iomanip.
using namespace std;
double f(double a, double b, double c, double d, double x) {
double z;
z =(a*(x*x*x))+(b*(x*x))+(c*x)+(d);
return (z);
}
double newton(double a, double b, double c, double d, double xn){
double z;
z = f(a,b,c,d,xn);
double fprime= f(a*0, 3*a, 2*b, c, xn);
double xnplus1 = xn - ((z)/(fprime));
return (xnplus1);
}
int main() {
double a,b,c,d,z;
double xn;
cout << "Input a" << endl;
cin >> a;
cout << "Input b" << endl;
cin >> b;
cout << "Input c" << endl;
cin >> c;
cout << "Input d" << endl;
cin >> d;
cout << "What is the initial guess?" << endl;
cin >> xn;
z = f(a,b,c,d,xn);
cout << z << endl;
double fprime = f(a*0, 3*a, 2*b, c, xn);
cout << fprime << endl;
double n=0;
double xnplus1 = newton(a,b,c,d,xn);
newton(a,b,c,d,xn);
cout << "xn" << xn << endl;
cout << "xnplus1" << xnplus1 << endl;
cout << "abs" << abs(xnplus1-xn);
while (abs(xnplus1-xn)>0.00001) {
if (n!=0) {
xn = xnplus1;
}else{
xn=xn;
}
double xnplus1 = newton(a,b,c,d,xn);
z = f(a,b,c,d,xn);
double fprime = f(a*0, 3*a, 2*b, c, xn);
newton(a,b,c,d,xn);
n++;
}
return 0;
}
|