Another thing is that you use pow(x1,2). The pow function isn't very efficient and it takes much less time to compute x1*x1. It's a good idea to use that instead when possible (and it saves some typing!).
#include <iostream>
#include <cmath>
typedefdouble (*func)(double); // func is now a pointer to a double f(double) function
// Returns f'(x) given a pointer to f, and value x.
double fprime( func f , double x)
{
constdouble dx = 0.000000001; // Theoretically, this should be infinitely close to 0
return ( f(x + dx) - f(x - dx) ) / (2*dx);
}
// Solves f(x) = 0 for x,
// Provide: function pointer f, a guess (x0), and the required precision.
double newtonRaphson( func f , double x0, double precision)
{
double x1 = x0 - f( x0 ) / fprime( f, x0 ); // <-- Newton's method right here!
if ( abs(x1 - x0) < precision )
return x1;
return newtonRaphson( f , x1 , precision ); // Recursion baby!
}
int main()
{
std::cout << newtonRaphson( cos , 1.6 , 0.0001) << std::endl;
std::cout << newtonRaphson( log , 1.5 , 0.0001) << std::endl;
return 0;
}
1.5708
1.0000
This gave me 1.5708 when evaluating cos(x) with a guess of 1.6. The real answer is pi/2 which is 1.5707963267948966.... We're within the precision required!
With the exception of our test functions cos and log, the only function from <cmath> that I used was double abs(double); which certainly isn't hard to make yourself.
So yeah, you can just use newtonRaphson() above and use it to evaluate any other functions you may be interested in.
Edit: Added some comments, and typedef'd double (*f)(double).
X1 unutilized? I'm not sure what unutilized is. Do you mean uninitialized?
Here are the problems with your function: double func(double&)
You don't specify a name for the double that comes in as an argument. I assume you want double& x1.
double f,pi,e,x1;
You had defined pi and e in the global scope already. You don't need to define them again. x1 is defined here, but should have been defined in the first line.
f=ln(pow(x1,2)+1)-(pow(e,0.4*x1)*cos(pi*x1);
While you've defined all of these variables, pi, e, and x1 aren't initialized. If you remove the pi and e definitions, then it will use the global scope variables which are good. x1 should have been in the first line. f is ok
}
You don't return a value. try putting return f; before this line.\
One more note, it's also not a good idea to delete your posts. You were probably brought to this forum from a google search when you were searching for answers. If you delete your OP, then no one else can see what we've suggested.