Issue with secant root finding c++
I am trying to wirte a program for school that will use the secant root finding method. The equation is:
( v / b ) ^2sin(alpha)= kr * Ts^4 +Uc *Ts -q
and I have to find Ts.
Unfortunately the example i have been using as my base is not working for me :. The root it gives is -1.QNAN or something along those lines so i have a mistake in the secant method somewhere, I am a novice at C++ so i am having a lot of trouble fixing this. Any help will be appreciated, also if someone can tell me the codes to make it easier to post code, i would greatly appreciate it. Thanks here is my code so far:
#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;
void secant (double, double, double, double, double, double, double, double, double, double, double, int);
double fx(double, double, double, double, double, double, double);
const double tol=0.0001; // Tolerance for convergence
const int max_iter=50; // Maximum iterations allowed
int main ()
{
double kr, uc, q, b, radians, Ts, x0, x1, root;
int iteration;
const double PI = 4.0*atan(1.0);
ifstream datain ("shuttle.txt");
ofstream dataout ("results.txt");
datain >> kr >> uc >> q >> b;
int velocity = 16000;
double angle =10;
x0= 1000;
x1 = 200;
for (int velocity = 16000; velocity <= 17500; velocity += 500) {
for (int angle = 10; angle <= 70; angle += 15) {
radians= angle * PI/180 ;
cout << velocity << endl;
cout << radians << endl;
cout << angle << endl;
secant (angle, radians, velocity, kr, uc, q, b, Ts, x0, x1, root, iteration);
}
}
system("pause");
return 0;
}
void secant(double angle, double radians, double velocity, double kr, double uc, double q, double b, double Ts, double x0, double x1, double root, int iteration)
{
double xnminus1, xnplus1, xn;
iteration=0;
xnminus1=x0;
xn=x1;
do
{
++iteration;
xnplus1 = xn - fx(kr, uc, Ts, q, velocity, radians, xn)*(xn-xnminus1)/
(fx(kr, uc, Ts, q, velocity, radians,xn)-fx(kr, uc, Ts, q, velocity, radians,xnminus1));
cout<<"x"<<iteration+1<<" = "<<xnplus1<<endl;
xnminus1 = xn;
xn=xnplus1;
}
while ((fabs(fx(kr, uc, Ts, q, velocity, radians, xnplus1)) >= tol )&& (iteration < max_iter))
;
root=xnplus1;
cout<<"\nThe root is = "<<root<<endl;
cout<<"The number of iterations was = "<<iteration<<endl;
cout<<"The value of f(x) at the root = "<<fx(kr, uc, Ts, q, velocity, radians, root) <<endl<<endl;
}
double fx(double kr, double uc, double Ts, double q, double velocity, double b, double radians)
{
return kr * pow(Ts, 4.0) + uc * Ts - q - pow(velo开发者_开发问答city/b, 2.0) * sin(radians);
}
You use Ts without defining it. Funny that it is highlighted in blue... I think there is a senior SO user chuckling to himself somewhere...
精彩评论