Calculating the next value of sin(x) from previous sin.

582 Views Asked by At

(Please bare with me as I try to explain my problem to the best of my abilities)

I have a computer program that draws a sine. Each y value of the sine is stored against the x value in an array like so:

float sine[x] = y;

To find the value of my points, I iterate through each value of x from 0 to 799 using a for loop like so:

etime = 1000000;

int x;
for (x = 0; x < 800; ++x)
{
    sine[x] = sin((x + etime) / 300);
}

Is there anyway I could find the value of sine[x + 1] by using the value of sine[x]?

I want to avoid computing sin((x + etime) / 300) for everypoint on the graph as it costs a lot of memory.

EDIT 1

OK so I trie implementing the solution provided but I realized that I simplified my equation too much for the results to work. This is actually how the equation is calculated:

for(k = 0; k < 799; ++k)
{
    sinewave[k] = 145 * sin((0.984736 * k + etime) / 300) + 0.847563;
}

How do I calculate sinewave[k + 1] if I know sinewave[k]?

3

There are 3 best solutions below

0
On BEST ANSWER

So I ended using this trig identity to replace the sin call:

sin(a+b) = sinAcosB + sinBcosA.

I was able to precompute all the values and store them in lookup tables which lowered my sin function call count from 12800 calls down to 8 calls per frame.

3
On

Yes there is. Use this recurrence relationship

$$ \text{sine}[x+2] = \alpha\, \text{sine}[x+1] + \beta \,\text{sine}[x]$$ where $\alpha$ and $\beta$ depend on the resolution.

If you need more help, leave me a comment and I can show you how to find $\alpha$ and $\beta$

Added based on OP's request.

Let sine[x] = sin(t), sine[x+1]= sin(t+\delta) and sine[x+2]= sin(t+ 2\delta)

$$ \sin(t+2\delta)+\sin(t) = \\\sin(t+\delta) \cos(\delta) + \cos(t+\delta)\sin(\delta) + \sin(t+\delta)\cos(\delta) - \cos(t+\delta)\sin(\delta)$$ So $$\text{sine}[x+2] = 2 \cos{\delta} ~~\text{sine}[x+1] - \text{sine}[x] $$

In your case $\delta = \text{etime}/300$. So $$ \alpha = 2 \cos ( \text{etime}/300),~~\beta = -1$$

0
On

Have you tried solving the IVP: y'' = -y ; y'(0)= 1 ; y(0)=0 , numerically? The IVP has the unique solution of y(x) = sin(x) and there are a ton of tools for solving IVPs numerically.

You can express the second order ODE as a system of ODEs, let u = y' , then you can have the system

y' = u

y'' = u' = -y

Then use something like the Euler method for systems of ODEs which will let you solve for y(x)=sin(x) at each x: http://people.wallawalla.edu/~ken.wiggins/341w2008/LectureNotes/systemsofdifferentialequationsoutline.pdf

(there's better methods but Euler's method is relatively simple and I don't have any references on me, also that reference specifically solves the system for sin(x) )