Search code examples
c#trigonometrycurve-fittingdata-fittingmathnet-numerics

How to fit f(x) = sin(x)*sin(x) function to your data?


I'm trying to fit f(x) = sin(x)*sin(x) function to my data, but I can not accurately do that: fitting result

My data could have random phase shift and that is the main problem with this fitting.

I use MathNet.Numerics library. My code for fitting:

Func<double, double> f = Fit.LinearCombinationFunc(
xData,
yData,
x => 1.0,
x => Math.Pow(Math.Sin(x + 1.0), 2));

Solution

  • I found a solution for non linear fitting. You can use CenterSpace.NMath library and do the folowing(for i.e. f(x) = a + c*sin(x+b)*sin(x+b) ):

    DoubleParameterizedFunction func = new Function();
    
    var f = new DoubleParameterizedDelegate(
    func.Evaluate);
    
    var fitter = new OneVariableFunctionFitter<TrustRegionMinimizer>(f);
    DoubleVector x = new DoubleVector(xData);
    DoubleVector y = new DoubleVector(yData);
    DoubleVector init = new DoubleVector("100.0 1.0 100.0");
    DoubleVector solution = fitter.Fit(x, y, init);
    

    And Function() looks like that:

     public class Function : DoubleParameterizedFunction
        {
            public Function ()
            { }
    
            public override double Evaluate (DoubleVector p, double x)
            {
                double a = p[0];
                double b = p[1];
                double c = p[2];
                return a + c*Math.Sin(b + x) * Math.Sin(b + x);
            }
    
            public override void GradientWithRespectToParams (DoubleVector p,
              double x, ref DoubleVector grad)
            {
                double a = p[0];
                double b = p[1];
                double c = p[2];
                grad[0] = 1; //partial differential for a
                grad[1] = 2 * c * Math.Sin(x + b) * Math.Cos(x + b);  //partial differential for b
                grad[2] = Math.Sin(x + b) * Math.Sin(x + b);  //partial differential for c
            }
        }
    

    https://www.centerspace.net/doc/NMath/user/nonlinear-least-squares-86564.htm