This is a specific function which can be modified for any PDF you like. (It looks horrible because i wrote it.) Set PrintDistributionAndFitOpt -> True to see the plot. Otherwise it just returns the fit.
Clear[GetGaussianFitToDataDistribution];
Options[GetGaussianFitToDataDistribution] = {
UseNumberBinsOpt -> 50
,PrintDistributionAndFitOpt -> False
};
GetGaussianFitToDataDistribution[InData_List, OptionsPattern[]] := Module[{
UseNumberBins, PrintDistributionAndFit
, DataScore, MaxBin, MinBin, BinWidth, UseBins
, wsigma, wmu, x, wFit
},
{UseNumberBins, PrintDistributionAndFit} = OptionValue[{UseNumberBinsOpt, PrintDistributionAndFitOpt}];
If[EvenQ[UseNumberBins], UseNumberBins++;];
If[Length[InData] < UseNumberBins
, Print["Warning in GetGaussianFitToDataDistribution: Less data than bins."];
];
(* Determine the bins *)
MaxBin = Ceiling[Max[InData]];
MinBin = Floor[Min[InData]];
BinWidth = N[(MaxBin - MinBin)/UseNumberBins];
UseBins = Range[MinBin + 0.5*BinWidth, MaxBin, BinWidth];
(* Generate data to be fit using BinCounts
- normalize to 1.0 or the optimization gets confused
*)
DataScore = Transpose[{UseBins
, (N[#] &) /@ BinCounts[InData, {MinBin, MaxBin, BinWidth}]
}];
DataScore = ({#[[1]], #[[2]]/Max[DataScore[[All, 2]]]} &) /@
DataScore;
(*Print[DataScore];*)
(* Find the Best Fit
- Uses Mean and StDev for estimates of the partameters
*)
wFit = NonlinearModelFit[DataScore
, PDF[NormalDistribution[wmu, wsigma], x]/
PDF[NormalDistribution[wmu, wsigma], wmu]
, {{wmu, Mean[InData]}
, {wsigma, StandardDeviation[InData]}}, x];
If[PrintDistributionAndFit, Print[Show[{
ListPlot[DataScore, PlotStyle -> Darker[Red], PlotRange -> All
, PlotLegends -> Placed[{"Original Data"}, {0.85, 0.85}]
]
, Plot[wFit[x], {x, MinBin, MaxBin}
, PlotLegends -> Placed[{"Fitted Gaussian"}, {0.85, 0.75}]
]
}
, PlotLabel -> ToString[{wmu, wsigma} /. wFit["BestFitParameters"]]
<> "\t Samples = " <> ToString[Length[InData]]
, FrameLabel -> {"Bin Mid-Line", "Relative Frequency"}
]];
];
{wmu, wsigma} /. wFit["BestFitParameters"]
];
(*
TestData=RandomVariate[NormalDistribution[1000.,20.],10^5];
GetGaussianFitToDataDistribution[TestData
,PrintDistributionAndFitOpt\[Rule]True
,UseNumberBinsOpt\[Rule]50
]
*)
x = Table[RandomReal[L], {x, 0,Ns}];
the x on the RHS is superfluous, and likely to cause problems. All you need is:x = RandomReal[10, 10^4];
Second, your random data sf is constrained to lie between 0 and 2 (i.e. is bounded). Your pdf is not bounded (or if it is, it is not stated). Third, even if your density was unbounded, it does not integrate to unity, so is not well-defined. All that leaves aside the fact that the density does not fit the data. $\endgroup$skd = SmoothKernelDistribution[sf, Automatic, {"Bounded", {0, 2}, "Gaussian"}]; Show[Histogram[sf, {0.05}, "PDF"], Plot[{(15 Sqrt[5]/8) k^2/(k^2 + 1)^(5/2), PDF[skd, k]}, {k, 0, 2}]]
. $\endgroup$