How do I find the derivative of sin(x) where x could be any value e.g. 1,2,3 using recursion?
Asked
Active
Viewed 2,816 times
0
-
3What makes you think that recursion is a feasible approach to evaluating a trigonometric function? – jason Nov 28 '09 at 15:53
-
Add some clarification in your description. Why do you need to use recursion? Are you not allowed to use the c standard math library functions? Does the answer need to be very precise? – A. Levy Nov 28 '09 at 15:55
-
@Jason, why would it not be feasible? You could write a recursive function to evaluate terms in the taylor series expansion of the cosine, and terminate after reaching a set precision. – A. Levy Nov 28 '09 at 15:58
-
9**please at least try** to use full English words. It's a matter of respect for your readers (and no, I'm not a native English speaker, but I do care about the quality of the language we use to communicate with each other). – Kris Nov 28 '09 at 16:02
-
3I fail to see how this isn't a real question (3 close votes for that), albeit poorly worded but since when did we punish people for not having English as their first language? – cletus Nov 28 '09 at 16:05
-
Oh and FYI I think I've demonstrated that recursion is a perfectly viable approach to solving this problem. – cletus Nov 28 '09 at 16:16
-
Recursion is not a good choice. I would see: http://stackoverflow.com/questions/523531/fast-transcendent-trigonometric-functions-for-java – Mitch Wheat Nov 28 '09 at 16:20
-
@Mitch: I think the point is that constraints are given on the solution. – cletus Nov 28 '09 at 16:37
1 Answers
8
Firstly, the derivative of sin(x) is cos(x) or, to put it more formally:
f(x) = sin(x)
f'(x) = cos(x)
I guess you could solve sin(x) using the Taylor series for cos(x):
cos(x) = 1 - x^2/2| + x^2/4! + ...
with recursion. In Java:
public double cos(double x) {
return 1 + next(-x*x/2, x, 3);
}
public double next(double term, double x, int i) {
double next = -term * x * x / (i * (i + 1));
return term + next(term, x, i + 2);
}
Of course you'll need to put some limiter in to exit the recursion otherwise you'll get a stack overflow error eventually, which is left as an exercise for the reader.
Oh and I see the question is tagged as C not Java, but it is homework. :-)

Glorfindel
- 21,988
- 13
- 81
- 109

cletus
- 616,129
- 168
- 910
- 942
-
actually, you very rarely want to evaluate cos(x) using taylor series using the formula you gave. That expansion is around 0, and is generally a good approximation for "small" x (i.e. |x|<1). If you try large x you will quickly notice that since you have only finitely many terms you will break the condition that |cosx|<=1. Usually, you want to use taylor series by expanding around a known easy point close to the actually value that you are looking for. – ldog Nov 29 '09 at 08:54