I have a function (from here) that calculates the coordinate Y when given X
function calculateSinYGivenX(time, frequency = 1, amplitude = 1, phase = 0, offset = 0) {
return Math.sin((time * frequency * (Math.PI * 2)) + (phase * (Math.PI * 2))) * amplitude + offset;
}
So far my tests pass as expected
expect(calculateSinYGivenX(time = 0, frequency = 1, amplitude = 1, phase = 0, offset = 0)).toEqual(0);
expect(calculateSinYGivenX(time = 0.25, frequency = 1, amplitude = 1, phase = 0, offset = 0)).toEqual(1);
expect(calculateSinYGivenX(time = 0.5, frequency = 1, amplitude = 1, phase = 0, offset = 0)).toBeCloseTo(0);
expect(calculateSinYGivenX(time = 0.75, frequency = 1, amplitude = 1, phase = 0, offset = 0)).toEqual(-1);
expect(calculateSinYGivenX(time = 1, frequency = 1, amplitude = 1, phase = 0, offset = 0)).toBeCloseTo(0);
To illustrate:
When I try to shift the wave to the right (phase = 0.5), they fail
expect(calculateSinYGivenX(time = 0, frequency = 1, amplitude = 1, phase = 0.5, offset = 0)).toEqual(-1);
expect(calculateSinYGivenX(time = 0, frequency = 1, amplitude = 1, phase = 1, offset = 0)).toEqual(0);
expect(calculateSinYGivenX(time = 0, frequency = 1, amplitude = 1, phase = 1.5, offset = 0)).toEqual(1);
Expected -1.2246467991473532e-16 to equal -1
Expected 2.4492935982947064e-16 to equal 0
Expected -3.6739403974420594e-16 to equal 1
To illustrate:
I'm unfortunately not good enough at maths to figure out where I'm going wrong. I've used online sources to get to this point, but I can't seem to get it to work as expected.
After reading and testing few things, phase is just the starting time, so it can be understood as 'time offset'.
As a result, the composition of time + phase will always give the same result (for fixed frequency, amplitude and offset)
For example :
console.log(calculateSinYGivenX(time = 0.25, frequency = 1, amplitude = 1, phase = 1.26, offset = 0));
console.log(calculateSinYGivenX(time = 1.26, frequency = 1, amplitude = 1, phase = 0.25, offset = 0));
console.log(calculateSinYGivenX(time = 1.50, frequency = 1, amplitude = 1, phase = 0.01, offset = 0));
=>
-0.06279051952931265
-0.06279051952931265
-0.06279051952931265
So things are working as expected for the phase variable.
Be careful of floating point variable handle in JS, you used the toBeCloseTo(x) function, so I suggest you to use it for your comparisons.