- #1
SolStis
- 12
- 0
Hi, I've written code to resolve the routes of a function using the bisection method. The code works for the current route brackets (xb and xt) and for a decimal place value of 2. However when the decimal place value is changed the loop gets stuck. Code below:
#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
//declaration and initiation of fixed variables
double m=5.0,L=0.6,k=1000.0,g=9.81;
//Setup of function to be solved
double f(double x){
return tan(x)-sin(x)-(m*g)/(k*L);
}
//Main function
int main(){
//Declaration of decimal places var d
int d;
//Declaration of upper, lower and middle limit vars
double xb,xt,xm,dp;
//Promt user to input no. dec places of accuracy
cout << "Please input the number of decimal places to which the calculation will be accurate to.. " << endl;
cin >> d;
//Declaration of count var i
int i;
//Setup of initial route bracket and decimal place var dp
xb=0.5;
xt=1.0;
dp=pow(0.1,d);
double ans;
do{
xm=(xb+xt)/2;
ans=f(xm);
if((f(xb)*f(xt))>0){
xb=xm;
}
else{
xt=xm;
}
i++;
}
while ((ans>dp)||(ans<-(dp)));
cout << endl << i << " " << xm << " " << ans;
}
Any resolution to this would be greatly appreciated
Thanks
Sol
#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
//declaration and initiation of fixed variables
double m=5.0,L=0.6,k=1000.0,g=9.81;
//Setup of function to be solved
double f(double x){
return tan(x)-sin(x)-(m*g)/(k*L);
}
//Main function
int main(){
//Declaration of decimal places var d
int d;
//Declaration of upper, lower and middle limit vars
double xb,xt,xm,dp;
//Promt user to input no. dec places of accuracy
cout << "Please input the number of decimal places to which the calculation will be accurate to.. " << endl;
cin >> d;
//Declaration of count var i
int i;
//Setup of initial route bracket and decimal place var dp
xb=0.5;
xt=1.0;
dp=pow(0.1,d);
double ans;
do{
xm=(xb+xt)/2;
ans=f(xm);
if((f(xb)*f(xt))>0){
xb=xm;
}
else{
xt=xm;
}
i++;
}
while ((ans>dp)||(ans<-(dp)));
cout << endl << i << " " << xm << " " << ans;
}
Any resolution to this would be greatly appreciated
Thanks
Sol