Hello, I am trying to write a program that gives me a root of the function using Newton Rhapson method. Currently I am trying to write it in the int main() function to make it work. Afterwards I want to transfer the iteration to root function as thats what my assignment asks. A problem is this : write equation f(x) = 0 solution program. Show program's success by finding the root of function f(x) = 1 - x^2. The program should be made of three functions int main(), void rood(double& x, double eps) and double fk(double x). So, below is what I wrote. It doesn't seem to be a hard problem, but when I run the program I get the root to be equal to nan , which I know is a mistake. Can someone point me out to the right direction where I might be doing it wrongly trying to first write an iteration in function int main()? Thank you for all the help. All suggestions are welcome. Also, how I can find a derivative of a function without writing it as a different function? Is it possible?
I changed my function and it works now, but I am curious to know how to write derivatives in C++ without calling a function? Is it possible in my case?
Thanks, lastchance. However, I would like to keep fk(x) function and remove fk_p() which basically gives the derivative of fk(x). I want the derivative to be calculated in root() function without fk_p(x) function available or used. Any ideas?
I would like to keep fk(x) function and remove fk_p() which basically gives the derivative of fk(x). I want the derivative to be calculated in root() function without fk_p(x) function available or used. Any ideas?
So, in root(), where you update x, just put
1 2 3
constdouble SMALL = 1.0e-10;
double derivative = ( fk( x + SMALL ) - fk( x - SMALL ) ) / ( 2.0 * SMALL );
x = x_1 - fk(x_1) / derivative;
Then you don't need function fk_p() at all and you only have to change fk() if the function changes.