I tried to fit some data with boundary conditions, but FindFit
just could not work. Does anyone know the reason?
Details:
The function to be fitted is A*Tanh[x+a]+B
. Data is provided from x=0
to some positive number.
I set the requirement that the fitted function should be same as Tanh[x]
at x=0
both for its value and its first derivative.
I realized such a condition in FindFit
through a direct setting; however, it does not seems to work, i.e. the function is NOT exactly connected to the expected one. There is still about 10^-7 to 10^-10 difference between the two.
Following is my code and result
tL = Transpose[{Range[0, 5, .5], Tanh[#] & /@ Range[0, 5, .5] + RandomReal[.2, 11]}];
f = Tanh[x]; fD = D[tf, {x, 1}];
fitf = A*Tanh[x + a] + B; fitfD = D[fitf, {x, 1}];
fitf0 = fitf /. x -> 0; fitfD0 = fitfD /. x -> 0;
fit = FindFit[tL, {fitf, {fitf0 == 0, fitfD0 == 1}}, {{a, 0}, {A, 1}, {B, 0}}, x];
fitf=fitf/.fit;
F = Piecewise[{{f, x < 0}, {fitf, x >= 0}}]
FD = D[F, {x, 1}]
Show[Plot[F, {x, -6, 6}, PlotStyle -> Red, AxesLabel -> {x, "f(x)"}],ListPlot[tL], PlotRange -> All]
Limit[F, x -> 0, Direction -> -1]
Plot[FD, {x, -1, 1}, AxesLabel -> {x, "f'(x)"}]
AccuracyGoal
andPrecisionGoal
inFindFit
. For example forAccuracyGoal -> 12
andPrecisionGoal -> 12
I getfitf /. x -> 0 === 1.38778*10^-17
and(fitfD /. x -> 0) - 1 === -1.11022*10^-16
. $\endgroup$AccuracyGoal
,PrecisionGoal
andWorkingPrecision
under "More Information" in the documentation ofPrecisionGoal
orAccuracyGoal
. Basically,PrecisionGoal
is related to the absolute error in the estimated value, andAccuracyGoal
the to the relative error. $\endgroup$