#include
#include
double f(double n) {
/**
this function is --> f(x) = lhs - rhs
if lhs-rhs = 0, then x must be our answer
our task right now is to find x's value that will gives root
**/
double lhs = (n-5) / n;
double rhs = pow(5 / n, sqrt(2 * n + 2));
return lhs - rhs;
}
double secant_method(double Xn, double Xn_prev) {
/**
If the equation is impossible to solve using explicit analytical method,
then we must rely on using numerical analysis method.
There are three possible methods :
1) Bisection method (require x0 and x1, where x0 < x1)
2) Secant method (require x0 and x1, where x0 < x1)
3) Newton method (requires x0 only)
*x0 and x1 is values that are close enough to the root
Newton method is what student usually taught at school, but in order
to use that method, we must do a derivative to f(x).
If somehow f(x) is hard to do a derivative, we must rely on the
other two methods which either Bisection or Secant method.
Bisection method is the slowest among all as it converges too slowly.
Secant is considered in the middle in term of speed between Newton and Bisection method.
So, in this problem, I chose secant method as to differentiate f(x) is just too hard.
In term of converge speed:
Bisection method < Secant method < Newton method
Reference:
www.math.ust.hk/~machas/numerical-methods.pdf (See Chapter 2)
**/
double left_upper = (Xn - Xn_prev) * f(Xn);
double left_bottom = f(Xn) - f(Xn_prev);
return Xn - left_upper / left_bottom;
}
double loop(int count) {
/**
Xn_prev and Xn must be close enough to the root
for us to estimate the real root value.
For choosing these two value, you can throw the
equation into graphing calculator and see where will the
function hits zero. Choose any two value which near that root (zero)
And Xn_prev < Xn for initial in order for Secant method to converge to the root.
**/
double Xn_prev = 6.0;
double Xn = 6.1;
// iteratively find approximation to the root
for(int i=0; i