mardi 28 mars 2017

How to fix the do-while loop containing function calls

HI I'M A BEGINNER ON C++, I LITERALLY STARTED FROM SCRATCH. SO I BADLY NEED HELP FROM EXPERTS.

THERE SEEMS TO BE A PROBLEM IN MY DO-WHILE LOOP. SETTING ASIDE ANY PHYSICAL DEFINITION OF THE FUNCTION I HAVE RIGHT NOW, THE USER SHOULD INPUT THE COEFFICIENTS OF THE CUBIC FUNCTION, I.E. a,b,P, AND T. THE USER THEN WILL INPUT THE INITIAL GUESS, v1

NOW AT THE LOOP, I WILL STORE v1 TO v, THEN COMPUTE THE NEW VALUE OF v1 BY THE FORMULA: v1 = v - (fv/fv1) WHERE THE VALUES OF fv AND fv1 ARE DETERMINED FROM THE FUNCTION CALLS. THE RESULTS ARE DISTURBING AF.

PLEASE HELP ME GUYS ON MY LOOP! ALSO, PLEASE COMMENT ON MY FUNCTION DEFINITION. I JUST MADE THAT UP AFTER READING BASIC TUTORIALS.

THANK YOU GUYS!

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;

}

Aucun commentaire:

Enregistrer un commentaire