Root Finding

What is wrong with this program? It says it won't respond.


//Matthew HW7 Root Finding
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
using namespace std;
const double k=1.25*exp(9);//spring constant in grams per second squared
const double c=1.40*exp(7);//dampening coefficient in grams per second
const double m=3000*(1/(2.2 ));//mass of car in kilograms
const double x0=10*(1/(0.0254));//depth of pothole in meters
double fcn(double t);
void inputData(double&tLeft,double&tRight);
bool bisect(double& Left,double& Right);
void outputData(ofstream& outfile, double tLeft, double tRight);


int main(){
double x=0;
double tLeft=0;
double tRight=0;
int iterations=0;//number of iterations
ofstream outfile("HW7Results.txt");
if(!outfile){
//if condition is true
cout<"Error: can't open file.";
return 1;
}else{
inputData(tLeft, tRight);
outfile<<"iter...position(right)"<<endl;
outfile<<" iterations "<<""<<tLeft<<""<<tRight<<" "<<fcn(tLeft)<<" "<<fcn(tRight)<<endl;
}
while(!bisect(tLeft,tRight)&& tLeft-tRight>0.000001){
//if condition is true
iterations ++;
outfile<<iterations<<" "<<tLeft<<" "<<tRight<<" "<<fcn(tLeft)<<" "<<fcn(tRight)<<endl;

}if(bisect(tLeft,tRight)){
cout<<"No Rout.";
}else{
cout<<"The root is "<<tLeft;
}
outfile.close();
return 0;
}
void inputData(double& tLeft, double& tRight)
{
inputData(tLeft, tRight);
cout<<"Please enter the lower limit:";
cin>>tLeft;
cout<<endl<<"Please enter upper limit:";
cin>>tRight;
cout<<endl;
}
void outputData(ofstream& outfile, double tLeft, double tRight)
{
outfile<<"iter"<<" "<<"time(left)"<<" "<<"time(right)"<<" "<<"position(left)"<<" "<<"position(right)";
return;
}
double fcn(double t)
{
double x=0;
double n=c/2*m;
double s=0;
x=(exp(-n*t))*(x0*cos(s*t)+x0*(n/s)*sin(s*t));
s=sqrt((k/m)-(c*c)/(4*m*m));
return x;
}
bool bisect(double& Left, double& Right)
{
if(fcn(Left)*fcn(Right)>0){
return 1;

double mid=(Left+Right)/2;
if (fcn(Left)*fcn(Right)<0){
Right=mid;
}
Left=mid;
return 0;
}
}
It says it won't respond.
What does that mean?
Crikey, the depth of that pothole!

Unless you are into recursion, the first statement in routine inputData() shouldn't be ... inputData().

I think tLeft - tRight is invariably negative, so have a look at that conditional statement.

In routine bisect(), in the bisecting case you should be comparing function signs at either left and mid or mid and right, not left and right as you have at present.

On the non-c++ side, you are an engineering student: put your input in consistent and correct mass, length and time units, preferably kg, m, s. Your expression for n is also wrong: it's missing brackets round the denominator (2*m). And you are using the damped frequency S BEFORE you actually work it out.

Please PUT YOUR CODE IN CODE TAGS: this is not the first time you've been asked to do that.
Last edited on
Topic archived. No new replies allowed.