I've got some problems with my code, and I try to make it faster. Some of you suggested me to split my problem, and I'm here...
I post the same function with and without Compile.
This is a support function and does not involve my question
r=8.314472
fug1 = Compile[{v, p, t, a, b},
Module[{y, z, vbv, vb, f1, f2, f3, f4, f},
y = b/(4 v);
z = (p v)/(r t);
vbv = Log[(v + b)/v];
vb = v + b;
f1 = (4.*y - 3.*y^2.)/(1 - y)^2.;
f2 = (4.*y - 2.*y^2.)/(1 - y)^3.;
f3 = (2.*vbv)/(r t*b)*a;
f4 = (vbv/b - 1./vb)/(r t)*a;
f = f1 + f2 - f3 + f4 - Log[z];
Exp[f]]]
g2 doesen't work and I don't know why
g2 = Compile[{p, t, a0, a1, a2, b0, b1, b2},
Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},
a = a0*Exp[a1*t + a2*t^2];
b = b0 + b1*t + b2*t^2;
csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +
b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);
vol = NSolve[csd == 0. && v > 0., v, Reals] // Quiet;
sol = v /. vol;
vliquid = Min[sol];
vvapor = Max[sol];
fl = fug1[vliquid, p, t, a, b];
fv = fug1[vvapor, p, t, a, b];
Print[{t, p, vol, Abs[fl - fv]}];
Abs[fl - fv]],
RuntimeAttributes -> {Listable}]
This works without Compile!
g[p_?NumericQ, t_?NumericQ, a0_?NumericQ, a1_?NumericQ, a2_?NumericQ,
b0_?NumericQ, b1_?NumericQ, b2_?NumericQ] :=
Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},
a = a0*Exp[a1*t + a2*t^2];
b = b0 + b1*t + b2*t^2;
csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +
b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);
vol = NSolve[csd == 0. && v > 0., v, Reals];
sol = v /. vol;
vliquid = Min[sol];
vvapor = Max[sol];
fl = fug1[vliquid, p, t, a, b];
fv = fug1[vvapor, p, t, a, b];
Print[{t, p, vol, Abs[fl - fv]}];
Abs[fl - fv]];
g works very well and is the same of g2!
FindRoot[g[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,
7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,
34.376}] // Timing
g2 doesen't work
FindRoot[g2[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,
7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,
34.376}] // Timing