Thanks for the replies guys. I'm not really looking for performance here, so the amount of iterations won't really matter to me. Couldn't I just use a static value to always start x
1 at? If performance isn't an issue then I don't see how much of a difference it could make.
Also
You take the answer from the last iteration (xn), stick it into the next iteration (xn-1)
I think you meant to switch those around.(?)
The main purpose of me doing this is for later calc classes actually. I'm not currently in any calculus courses but I like math and learn better by teaching myself of course with the help of you guys. Anyways, so that derivative function could be represented in code as
1 2 3 4 5 6 7 8 9
| double f(float a) { return Math.pow(a, 3) - 10; }
double deriv(float X) { double a = X; double h = 1e-10; return (f(a+h)-f(a))/h; } |
So I could, with a const value, 3, for x
1, create the newton method like so:
1 2 3 4 5
| double X = 3;
for(int i = 0; i < iterations; i++) { X -= (f(X)/(deriv(X))); } |
Edit: I made a really stupid mistake, give me second, fixing it
I didn't use X for a when calculating the derivative. God I'm so stupid sometimes..
I just tested this code and it works perfectly!
Regarding delt0r's comment, I do know what I'm doing... kind of. That's why I'm here, to understand it better. Thanks for the bisection method suggestion, I'll check that out too!