I am trying to use the least squares regression to fit a curve to a table of values representing a sine wave. Similar to the question: Least squares regression of sine wave
Except I want to fit a more general formula of: $a * \sin(b*x + c) + d$
So given a function table I want to get the coefficients $a, b, c, d$ that most resemble the table given. Later I want to turn this into a computer program so I want to automatize all of the logic.
The regression formula (if that's the way to name it) I used: $Minimize(\sum_{i=1}^n (a* \sin(bx_i + c) + d - y_i)^2)$
Based on this I got these two formulas for $a$ and $d$: The sums here iterate over the elements in the function table.
$z_i = \sin(bx_i + c)$
$a = \frac{n\sum y_i z_i - (\sum y_i) * (\sum z_i)}{n\sum (z_i^2) - (\sum z_i)^2}$
$d = \frac{(\sum y_i) * (\sum z_i)^2 - (\sum z_i) * (\sum y_i * z_i)}{n \sum (z_i^2) - (\sum z_i)^2}$
I defined $b$ by the period (named $p$) which I will learn to calculate later:
$b = \frac{2\pi}{p}$
What I am now stuck at is the phase shift $c$. Which if I calculate in a similar fashion as $a$ and $b$ is stuck in this horrible formula: $0 = \sum (\cos(bx_i + c) * a * z_i + d * \cos(bx_i + c) - y_i * \cos(bx_i + c))$
This later turns into
$2\sum y_i*\cos(bx_i + c) = a*cos(2c)\sum \sin(2bx_i) + a*\sin(2c)*\sum \cos(2bx_i) + 4d*cos(c) \sum \cos(bx_i)$
If I use the regression formula: $Minimize(\sum(\sin^{-1}(\frac{y_i - d}{a})-bx_i - c)^2)$
I get $c = \frac{\sum \frac{\arcsin(\frac{y_i - d}{a}) - bx_i}{\sqrt{a^2 - (d - y_i)^2}}} {\sum \frac{1}{\sqrt{a^2 - (d - y_i)^2}}} $
Is there any way to define $c$ from this last equation and simplify the above mentioned equations?
Demo of the problem: https://www.desmos.com/calculator/iyacah4ors