Secant Method Root Finder Loop Question

I tried to convert my secant method root finder to use a do-while loop but I can't get the answer I am expecting to get. Could someone help me fix my loop.

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
  #include <iostream>
#include <math.h>
#define m (9.1 * pow(10,-28)) // mass of an electron g
#define c (2.99792458 * pow(10,10)) // speed of light in a vacuum cm s-1
#define h (1.0546 * pow(10,-27)) // planck's constant cm2 g s-1
#define p (pow(3.1415926535,2))
#define Y 0.5 // neutron/proton ratio
#define N (6.02 * pow(10,23)) //avogadro's number
#define l (pow((h/(m*c)),3)) // lambda cm
#define P (4.86 * pow(10,26)) //pressure erg/cm^3
#define E 0.000000001
#define b ((m * pow(c,2))/((8 * p * l)))
#define a cbrt(3 * p * l * Y * N)
double f(double x)
{
    return ((b * ((((((0.66666666666)*(pow(x,3))) - (x))*((sqrt(1 + pow(x,2))))) + (log(((x) + (sqrt(1 + (pow(x,2)))))))))) - P);
}
using namespace std;
double x,fx,x1,x2,f1,f2,x3,x4;
int main(){
    cout<<"Blah blah blah \n";
    cout<<"x1? ";
    cin>>x1;
    cout<<"x2? ";
    cin>>x2;
    f1 = f(x1);
    f2 = f(x2);
    do
    {
        x3 =(x2 - ((((f2 * (x2-x1)))/(f2-f1))));
        x1=x2;
        f1=f2;
        x2=x3;
        f2=f(x3);
    }
    while (fabs((x3-x2)/x3)>0.0000000000001);
    
    x4 = ((pow(x3,3))/(a));
    cout<<x4;
    return 0;
}


This was my original loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Label:
    x3 =(x2 - ((((f2 * (x2-x1)))/(f2-f1))));
    if(fabs((x3-x2)/x3)>0.000001)
    {
        x1=x2;
        f1=f2;
        x2=x3;
        f2=f(x3);
        goto Label;
    }
    else
        (cout<<"The root is "<<x3<<".")<<endl;
    return(0);
}
Last edited on
> I can't get the answer I am expecting to get
then you should say
- what answer you are getting
- what answer you expect
- what input you are using


> return ((b * ((((((0.66666666666)*(pow(x,3))) - (x))*((sqrt(1 + pow(x,2))))) + (log(((x) + (sqrt(1 + (pow(x,2)))))))))) - P);
lisp


> 4.86 * pow(10,26)

use scientific notation 4.86e26
Last edited on
Topic archived. No new replies allowed.