I'm an Android programmer and am working on a graphing calculator. I have been looking for a formula for sine and cosine to put in there. I have a decent understanding of mathematics but can not seem to find this formula. Any help would be great, thanks.
Is there a formula for sine and cosine?
-
1I would just use some free library to do this. It's likely going to be much faster than anything you could write by hand. Unless you're just doing it for fun, in which case, knock yourself out! – 2016-02-13
4 Answers
You can express them using MacLaurin series or Taylor series expansions. You can find this on Wikipedia.
$\sin(x) = \sum_{n=0}^{\infty}\frac{(-1)^n}{(2n+1)!}x^{2n+1}= x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\ldots$
$\cos(x) =\sum_{n=0}^{\infty}\frac{(-1)^n}{(2n)!}x^{2n}=1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}+\ldots$
-
1This is too little information to be of use for a compute program. How many terms should be calculated? What pre-processing (range reduction) can be done on the parameter? How should the polynomial be calculated? And son. Can you add any of these details? Worst of all, another answer, previous to yours, already gives this information. What can you add to that other answer? – 2016-02-13
Are you sure you don't have access to java.lang.Math?
-
0Yes, thanks for pointing out that method. Knowing the formula doesn't hurt anyways though. – 2012-02-23
You might want to consider finite expressions too. Particularily
$ \cos \frac{\pi x}{2} \approx 4\frac{1-x^2}{4+x^4} \text{ ; for} -1
$\sin x \approx \frac{{16x\left( {\pi - x} \right)}}{{5{\pi ^2} - 4x\left( {\pi - x} \right)}} \text{ ; for } 0
They give a great approximation: see here.
-
0@Rusland Agreed. – 2016-02-13
The best-known formulas are the Taylor series:
\begin{align} \sin x & = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots \\[10pt] & = \sum_{n=0}^\infty \frac{(-1)^n x^{2n+1}}{(2n+1)!} \\[10pt] \cos x & = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots \\[10pt] & = \sum_{n=0}^\infty \frac{(-1)^n x^{2n}}{(2n)!} \end{align}
-
0@DavidMitra: There's a little problem with that method when it comes to arbitrary precision. You need to compute $π$ first. Also, even if you have $x = 1$, you would need $O(p/\log(p))$ multiplications if you want to get precision $2^{-p}$ because the error term is at least $1/n^n$ for $n$ terms and so you need $n \in Ω(p/\log(p))$. In contrast, if you use the identity I gave above, you reduce the computational complexity to $O(\sqrt{p})$ multiplications. There are faster known algorithms such as AGM, but this is an elementary way to use the Taylor expansion for efficient computation. – 2017-09-22