# FindFit with Replace error

I am trying to fit my data, and I keep having error messages as below. Could anybody help me to solve this problem? The codes are written after the error messages.

Oo = 3;
R = 8.314;
Wo = 15999;
Wh = 18001.8;
MW = 317127.7;
k1eqn[T_, dSox_, dHox_] = E^((-dHox + dSox (T + 273))/(R (T + 273)));
k2eqn[T_, dShyd_, dHhyd_] = E^((-dHhyd + dShyd (T + 273))/(
R (T + 273)));


This link is for the code of FullDataSet to fit. I couldn't add the dataset code as it's a lot of data. You can copy and paste the code in the link.

This is my fitting eqn. I know that I should use [[3,1,2]] or [[4,1,2]].

FullTestK1[ph2o_, po2_, k1_, k2_] := NSolve[Eliminate[
k1 == (p^2*Oo)/( po2^(1/2)* vo) &&
k2 == oh^2/(ph2o vo Oo ) &&
delM == ((Wo*(0.1 - vo)/MW) + (Wh*oh/(2*MW)))*100 &&
2 vo + oh + p == 0.2,
{p, vo, oh}], delM][[3, 1, 2]]

Fullfit =
FindFit[FullDataSet, {FullTestK1[ph2o, po2, k1eqn[T, dSox, dHox],
k2eqn[T, dShyd,
dHhyd]]}, {{dHox, -100000}, {dSox, -100}, {dHhyd, -100000},{dShyd, -100}}, {ph2o, po2, T}]


After I use FindFit, I keep having errors.

• Does Eliminate with [[3,1,2]] give the desired result? In other words, is the order of the results produced by Eliminate always what you want?
– JimB
Jun 1, 2022 at 5:20

To get things to work I changed the following: (1) = to := in the definitions of k1eqn and k2eqn, (2) Added ?NumericQ to the parameters in FullTestK1, (3) Changed FindFit to NonlinearModelFit so that you can find regression diagnostics and estimates of precision, and (3) scaled the parameters so that they are on approximately the same order of magnitude.

Oo = 3;
R = 8.314;
Wo = 15999;
Wh = 18001.8;
MW = 317127.7;
k1eqn[T_, dSox_, dHox_] := E^((-dHox + dSox (T + 273))/(R (T + 273)));
k2eqn[T_, dShyd_, dHhyd_] :=
E^((-dHhyd + dShyd (T + 273))/(R (T + 273)));

FullTestK1[ph2o_?NumericQ, po2_?NumericQ, k1_?NumericQ,
k2_?NumericQ] := NSolve[Eliminate[k1 == (p^2*Oo)/(po2^(1/2)*vo) &&
k2 == oh^2/(ph2o vo Oo) && delM == ((Wo*(0.1 - vo)/MW) + (Wh*oh/(2*MW)))*100 &&
2 vo + oh + p == 0.2, {p, vo, oh}], delM][[3, 1, 2]]

nlm = NonlinearModelFit[FullDataSet, {FullTestK1[ph2o, po2,
k1eqn[T, -100 dSox, -100000 dHox], k2eqn[T, -100 dShyd, -100000 dHhyd]]},
{{dHox, 1}, {dSox, 1}, {dHhyd, 1}, {dShyd, 1}}, {ph2o, po2, T}];


Based on the warning message, there are still issues. A summary of the fit follows:

nlm["ParameterTable"]


nlm["EstimatedVariance"]^0.5
(* 0.124062 *)


The histogram of the "FitResiduals" looks reasonably normal (Gaussian):

Histogram[nlm["FitResiduals"], "FreedmanDiaconis", "PDF"]


However, the plot of residuals vs the predicted values shows a pattern suggesting an inadequacy in the proposed model:

ListPlot[Transpose[{nlm["PredictedResponse"], nlm["FitResiduals"]}],
Frame -> True, FrameLabel -> {"Predicted response", "Residuals"}]